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轴为Counts。我使用以下代码进行了尝试
ax = plt.subplots()
rects1 = ax.bar(survived_df["Groups"], survived_df["Counts"], color='r')
plt.show()
但我收到以下错误
invalid literal for float(): 0-9
给该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()
请注意,您还可以将Pandas
绘图功能直接与一个衬管一起使用:
survived_df.plot('Groups', 'Counts', kind='bar', color='r')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句