Python 使用字典使用 matplotlib 绘制条形图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16010869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plot a bar using matplotlib using a dictionary
提问by otmezger
Is there any way to plot a bar plot using matplotlibusing data directly from a dict?
有什么方法可以matplotlib直接使用 dict 中的数据绘制条形图吗?
My dict looks like this:
我的字典是这样的:
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
I was expecting
我期待
fig = plt.figure(figsize=(5.5,3),dpi=300)
ax = fig.add_subplot(111)
bar = ax.bar(D,range(1,len(D)+1,1),0.5)
to work, but it does not.
工作,但事实并非如此。
Here is the error:
这是错误:
>>> ax.bar(D,range(1,len(D)+1,1),0.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/matplotlib/axes.py", line 4904, in bar
self.add_patch(r)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axes.py", line 1570, in add_patch
self._update_patch_limits(p)
File "/usr/local/lib/python2.7/site-packages/matplotlib/axes.py", line 1588, in _update_patch_limits
xys = patch.get_patch_transform().transform(vertices)
File "/usr/local/lib/python2.7/site-packages/matplotlib/patches.py", line 580, in get_patch_transform
self._update_patch_transform()
File "/usr/local/lib/python2.7/site-packages/matplotlib/patches.py", line 576, in _update_patch_transform
bbox = transforms.Bbox.from_bounds(x, y, width, height)
File "/usr/local/lib/python2.7/site-packages/matplotlib/transforms.py", line 786, in from_bounds
return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
TypeError: coercing to Unicode: need string or buffer, float found
采纳答案by David Zwicker
You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:
您可以通过首先绘制条形图然后设置适当的刻度线来分两行完成:
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
# # for python 2.x:
# plt.bar(range(len(D)), D.values(), align='center') # python 2.x
# plt.xticks(range(len(D)), D.keys()) # in python 2.x
plt.show()
Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys()))in python3, because D.keys()returns a generator, which matplotlib cannot use directly.
请注意,倒数第二行应该plt.xticks(range(len(D)), list(D.keys()))在 python3 中读取,因为D.keys()返回一个生成器,matplotlib 不能直接使用它。
回答by Michael T
For future reference, the above code does not work with Python 3. For Python 3, the D.keys()needs to be converted to a list.
为了将来参考,以上代码不适用于 Python 3。对于 Python 3,D.keys()需要转换为列表。
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
回答by Swaraj Kumar
The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label)where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_labeldoes the same work as xticks(). One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label). For detailed information please refer the documentation.
实现它的最佳方法是使用matplotlib.pyplot.bar(range, height, tick_label)范围为图中相应条形图的定位提供标量值的位置。tick_label做同样的工作xticks()。也可以用整数替换它并使用 multiple plt.bar(integer, height, tick_label)。有关详细信息,请参阅文档。
import matplotlib.pyplot as plt
data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())
#tick_label does the some work as plt.xticks()
plt.bar(range(len(data)),values,tick_label=names)
plt.savefig('bar.png')
plt.show()
Additionally the same plot can be generated without using range(). But the problem encountered was that tick_labeljust worked for the last plt.bar()call. Hence xticks()was used for labelling:
此外,无需使用range(). 但是遇到的问题是tick_label只适用于最后一次plt.bar()调用。因此xticks()被用于标记:
data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())
plt.bar(0,values[0],tick_label=names[0])
plt.bar(1,values[1],tick_label=names[1])
plt.bar(2,values[2],tick_label=names[2])
plt.xticks(range(0,3),names)
plt.savefig('fruit.png')
plt.show()
回答by anilbey
回答by ImportanceOfBeingErnest
回答by rwilsker
Why not just:
为什么不只是:
import seaborn as sns
sns.barplot(list(D.keys()), list(D.values()))


