用Matplotlib.pyp在python中绘制条形图

2024-09-26 18:03:36 发布

您现在位置:Python中文网/ 问答频道 /正文

   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

Tags: 代码dfmatplotlibbarpltaxcolorgroups
1条回答
网友
1楼 · 发布于 2024-09-26 18:03:36

plt.bar函数的第一个数组必须是对应于条左侧x坐标的数字。在您的情况下,[0-9, 10-19, ...]不被识别为有效参数。

但是,您可以使用数据帧的索引绘制条形图,然后定义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

相关问题 更多 >

    热门问题