【问题标题】:How to plot an histogram from 'groupby' and 'mean' functions如何从“groupby”和“mean”函数绘制直方图
【发布时间】:2019-02-16 17:54:52
【问题描述】:

我有一个这样的数据框:


使用不同的国家名称。
我想计算 Medium height 列的平均值并按 Country 列分组;然后我想在 xticks 上绘制一个包含所有国家/地区名称的直方图。

为此,我计算了平均值:height = df.groupby(["Country"]).mean()["Medium Height"] 我试图用以下方法绘制直方图:

plt.hist(height, density=1, facecolor="black", alpha=0.6)
plt.xticks(countries, df["Paese"])

但情节是这样的:

这是我使用的代码:

height = df.groupby(["Country"]).mean()["AMedium Height"]
countries = np.arange(152) # The number of countries
plt.hist(height, density=1, facecolor="black", alpha=0.6)
plt.xticks(countries, df["Country"])
plt.show()

-- 编辑--
这是我使用的数据框的一部分:

       Country  Year  Height
0  Afghanistan  1870   168.4
1  Afghanistan  1880   165.7
2  Afghanistan  1930   166.8
3      Albania  1880   170.1
4      Albania  1890   169.8

【问题讨论】:

  • 您能创建一个MVCE 来说明您的问题吗?准备一个带有部分数据的df 示例,例如df.head()
  • 第一张图片是df.head()的输出
  • 是的。要制作 MVCE,您需要将其转换为 smth。喜欢:df = pd.DataFrame([("Afghanistan", 1870, 168.4), ("Albania", 1870, 190)], columns="Country Year Weight".split())。帮助社区为您提供帮助!

标签: python pandas matplotlib


【解决方案1】:

您似乎想绘制平均高度与国家/地区的条形图。

你可以这样做

means = df.groupby(["Country"]).mean()['Height']
print(means)

结果

Country
Afghanistan    166.966667
Albania        169.950000
Name: Height, dtype: float64

然后像这样绘制它

ax = means.plot(kind = 'bar')
ax.set_ylabel('Mean Height')

结果

如果你想让所有的条都是相同的颜色,请使用

ax = means.plot(kind = 'bar', colors = 'grey')
ax.set_ylabel('Mean Height')

导致

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2015-08-26
    • 2018-04-18
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多