python - matplotlib中的条形图使用平均值吗?

标签 python pandas matplotlib

我有一个数据集df:

users  number   
user1   1          
user2   34       
user3   56      
user4   45      
user5   4
user1   3
user5   11
user1   3

制作这样的条形图时:

plt.bar(x['users'], x['number'].sort_values(ascending=False), color="blue")

在绘图过程中,它是否取 number 列中每个 user 的平均值? 如果我希望 number 列中所有数字的总和按降序显示在条形图中该怎么办?

我尝试过这个:

plt.bar(x['users'], x['number'].sum().sort_values(ascending=False), color="blue")

给出:

AttributeError: 'numpy.float64' object has no attribute 'sort_values'

代码:

import pandas as pd
df = pd.DataFrame({'number': [10,34,56,45,33],
'user': ['user1','user2','user3','user4','user1']})
#index=['user1','user2','user3','user4','user1'])
plt.bar(df['user'], df['number'], color="blue")

enter image description here

它总是为拥有多个值的用户保留最大的值。

最佳答案

我不确定这是否是您想要的,或者您是否希望首先对每个用户的值进行分组,然后按降序绘制总数。

x = x.sort_values('number',ascending=False)
plt.bar(range(len(x['users'])), x['number'], color="blue")
plt.xticks(range(len(x['users'])), x['users'])
plt.ylabel('Numbers')

输出

enter image description here

如果您想绘制每个用户的平均值,请使用以下代码:

x1 = x.groupby('users').mean().reset_index()
plt.bar(range(len(x1)), x1['number'], color="blue")
plt.xticks(range(len(x1)), x1['users'])
plt.ylabel('Mean')

输出

enter image description here

如果不排序或分组会怎样:所有条形都存在,但您看不到相同 x 值的不同条形,因为 alpha=1默认情况下。我使用 alpha=0.2 来强调我的观点。现在您可以看到在 user1 处有两个条形在彼此后面。

import pandas as pd
df = pd.DataFrame({'number': [10,34,56,45,51], 'user': 'user1','user2','user3','user4','user1']})
plt.bar(df['user'], df['number'], color="blue", linewidth =2, edgecolor='black' , alpha = 0.2)

输出

enter image description here

关于python - matplotlib中的条形图使用平均值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52277337/

相关文章:

python - 向 pandas 数据框中添加依赖于另一列的额外列

python - 在 Python 中使用 Matplotlib.image 时出错

Python/matplotlib : print to resolution and without white space/borders/margins

python - 如何在 MongoDB $projection 中使用 $map

python - Matplotlib 时间线

python - 如何将具有不规则列的html代码转换为嵌套的json文件?

python-3.x - 为什么 pandas.read_sql 返回一个空的 DataFrame?

python - 使用 matplotlib 绘制感知器算法

python - 从 df 创建一个包含两个特征的新数据框,其中行以一个特征为条件

python - OrderedDict 仅打算更新一个键值对时更新所有键值对