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 轴为计数。我用下面的代码试了一下
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')
关于python - 使用 Matplotlib.pyplot 在 python 中绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40319743/