python生成条形图-在Python中创建条形图

1586010002-jmsa.png

I have a couple of problems with the Bar Chart that I'm trying to create in python. My code for the chart looks like this:

import matplotlib

matplotlib.use('Agg')

from pylab import *

import calendar

def webshow(img):

savefig(img,dpi=500)

print 'Content-Type: text/html '

print '"'+img+''

genres = []

n = 0

for c in sorted_list:

genres.append(sorted_list[n][0])

n += 1

grosses = []

a = 0

for c in sorted_list:

grosses.append(sorted_list[a][1])

a += 1

clf()

bar(arange(len(grosses)),grosses)

xticks( arange(len(genres)),genres, rotation=80)

webshow("barchart.png")

My chart looks like this:

tumblr_ltk9v6xShD1r5te58o1_500.png

Basically my main problem is that the values are in decimals with scientific notation. I want to present them in millions if possible. Also, I'm not sure how to make it so the genres are not cut off at the bottom. Thank you for any help!

解决方案

First up, I would use a figure object to work on: this makes it easier to construct the plot to your liking. To construct your graph, the following should do:

fig = plt.figure()

fig.subplots_adjust(bottom=0.2) # Remark 1

ax = fig.add_subplot(111)

ax.bar(arange(len(grosses)), grosses)

ax.ticklabel_format(style='plain') # Remark 2

ax.set_xticks(arange(len(genres)))

ax.set_xticklabels(genres, rotation=80)

savefig('barchart.png', dpi=500)

Along with the following remarks:

This adjusts the size of your image, in this case it enlarges the bottom to be able to fit your labels. In most cases you roughly know the data you are going to put in, so that should suffice. If you are using matplotlib version 1.1 or higher, you could use the tight_layout function to do this automatically for you. The alternative is to calculate the needed size by yourself based on the bounding boxes of all axes labels as shown here, but you need a renderer for this to be able to determine the sizes of all labels.

By specifying the label format (using either sci or plain), you can change the rendering of the values. When using plain, it will just render the value as is. See the docs on this function for more info. Note that you can also use the set_yticklabels function's text argument to control the formatting further (of course that function is also available for the x axis.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值