gpt4 book ai didi

python - 如何根据 'groupby' 和 'mean' 函数绘制直方图

转载 作者:行者123 更新时间:2023-12-01 08:19:45 26 4
gpt4 key购买 nike

我有一个像这样的数据框:

Imgur
具有不同的国家/地区名称。
我想计算中等高度列的平均值并按国家列分组;然后我想绘制一个直方图,其中 xticks 上包含所有国家/地区的名称。

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

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

但是情节是这样的:
Imgur

这是我使用的代码:

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

最佳答案

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

你可以做到

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

结果

enter image description here

如果您希望所有条形颜色相同,请使用

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

结果

enter image description here

关于python - 如何根据 'groupby' 和 'mean' 函数绘制直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54726012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com