【问题标题】:I am not able to plot mean line over my bar graph which I made using unstack method我无法在我使用 unstack 方法制作的条形图上绘制平均线
【发布时间】:2019-09-29 14:39:16
【问题描述】:
total_group_sum.unstack().plot(kind='bar')

我可以绘制我的条形图,但是现在我想在它上面画一条水平平均线。我尝试使用axhline(),但出现错误:

ValueError:Series 的真值不明确。使用a.empty, a.bool()、a.item()、a.any() 或 a.all()。

如何在现有条形图上绘制水平平均线?

total_group_sum.unstack().plot(kind='bar')

<IMAGE OF BAR GRAPH (I AM NOT ABLE TO POST PHOTO HERE)>

mean = total_group_sum.mean()
plt = total_group_sum.unstack().plot(kind='bar')
plt.axhline(mean)

ValueError: The truth value of a Series is ambiguous. Use a.empty, 
a.bool(), a.item(), a.any() or a.all().

PS - 我正在使用 jupyter 笔记本

【问题讨论】:

  • 请发布您的数据样本

标签: pandas matplotlib plot bar-chart mean


【解决方案1】:

所以,我尝试使用随机数据重新创建我认为是您的问题:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


np.random.seed(123)
df = pd.DataFrame(
    {
        'a':np.random.randint(0,10,100),
        'b':np.random.randint(0,10,100),
        'c':np.random.randint(0,10,100),}
)

df.groupby('a').sum().unstack().plot(kind='bar')

我认为你的问题是,这一行:

mean = df.groupby('a').sum().mean()

返回每个组的平均值:

b    48.7
c    42.1
dtype: float64

然后,你打电话

plt.axhline(mean)

想要精确地绘制一条线,但你给了它几条线。你可以做两件事:

  1. 或者,绘制每个组的平均值:

    for m in mean:
        plt.axhline(m)
    
  2. 或者,计算平均值,然后绘制:

    plt.axhline(np.mean(mean))
    

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多