2016-10-29 61 views
2
Groups Counts 
1 0-9  38 
3 10-19 41 
5 20-29 77 
7 30-39 73 
9 40-49 34 

我想使用matplotlib.pyplot库创建一个条形图,其中包含x轴上的组和y轴上的计数。我尝试过了使用下面的代码使用Matplotlib.pyp在python中绘制条形图

ax = plt.subplots() 
    rects1 = ax.bar(survived_df["Groups"], survived_df["Counts"], color='r') 
    plt.show() 

但我发现了以下错误

invalid literal for float(): 0-9 
+0

明显(如错误消息告诉)数据类型你的组列与浮动不兼容。你的数据类型是什么?串?什么样的对象是'survived_df'。你使用熊猫吗?然后将其添加到标签! – dnalow

回答

5

给予plt.bar功能必须是对应的左侧边的x坐标号码第一阵列酒吧。在你的情况下,[0-9, 10-19, ...]不被认为是有效的参数。

然而,您可以使用DataFrame的索引制作条形图,然后定义x-ticks(您希望将标签放置在x轴上的位置)的位置,然后更改您的x刻度的标签组名称。

fig,ax = plt.subplots() 
ax.bar(survived_df.index, survived_df.Counts, width=0.8, color='r') 
ax.set_xticks(survived_df.index+0.4) # set the x ticks to be at the middle of each bar since the width of each bar is 0.8 
ax.set_xticklabels(survived_df.Groups) #replace the name of the x ticks with your Groups name 
plt.show() 

enter image description here

请注意,你也可以用一个衬垫直接使用Pandas绘图功能:

survived_df.plot('Groups', 'Counts', kind='bar', color='r') 

enter image description here