【问题标题】:Plotting a Bar Graph in python with Matplotlib.pyplot使用 Matplotlib.pyplot 在 python 中绘制条形图
【发布时间】:2017-03-12 05:04:57
【问题描述】:
   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

【问题讨论】:

  • 显然(如错误消息所示)您的组列的数据类型与浮点数不兼容。你的数据类型是什么?细绳? survived_df 是什么类型的对象。你用熊猫吗?然后将其添加到标签中!

标签: python matplotlib bar-chart


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2022-01-12
    • 2018-05-18
    • 2021-10-28
    • 2016-07-06
    相关资源
    最近更新 更多