在Python中创建条形图 [英] Creating Bar Charts in Python

查看:315
本文介绍了在Python中创建条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个问题的条形图,我试图在python中创建。我的代码如下:

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\n'
    print '<img width="800" height="400" src="'+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")

我的图表如下所示:

基本上我的主要问题是值是小数科学计数法。如果可能,我想要以百万的形式呈现他们。此外,我不知道如何使它,所以类型不是在底部切断。谢谢任何帮助!

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!

推荐答案

首先,我会使用 object to work on:这使得更容易根据你的喜好构建图。要构建图形,应该如下:

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)

随同以下备注:


  1. 这调整图像的大小,在这种情况下,它放大底部,以适应您的标签。在大多数情况下,你大致知道你要放入的数据,所以应该足够了。如果您使用的是matplotlib版本1.1或更高版本,则可以使用 tight_layout 功能自动为您执行此操作。另一种方法是根据所有轴标签的边界框自己计算所需的大小,如下所示:这里,但您需要一个渲染器,以便能够确定所有标签的大小。

  2. 通过指定标签格式(使用 sci plain ),您可以更改值的呈现。当使用 plain 时,它将仅显示该值。有关详细信息,请参阅此函数的文档。请注意,您还可以使用 set_yticklabels 函数的 text 参数进一步控制格式化(当然,该函数也可用于x轴。

  1. 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.
  2. 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.

这篇关于在Python中创建条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆