python - 使用 Matplotlib.pyplot 在 python 中绘制条形图

标签 python matplotlib bar-chart

   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()

enter image description here

请注意,您还可以直接使用 Pandas 的绘图功能:

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

enter image description here

关于python - 使用 Matplotlib.pyplot 在 python 中绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40319743/

相关文章:

python - 从 google.cloud.logging_v2 导入类型 ImportError : cannot import name types

python - matplotlib 特定数量的网格点的流图错误

matplotlib - 更改 View 、plot3D、Julia 语言(类似于 matplotlib)

python - 在 matplotlib 中向条形图添加面板

python - 有什么方法可以加快Seaborns Pairplot的速度

python - 遍历字典列表

python - 如何在 Python 3 中获取导入包的位置?

python - Matplotlib:检查是否未定义显示

python - 带有 matplotlib 的长垂直条形图

python - Groupby 和绘制条形图