【问题标题】:Mean line on top of bar plot with pandas and matplotlib使用 pandas 和 matplotlib 在条形图顶部的平均线
【发布时间】:2016-01-16 15:29:02
【问题描述】:

我正在尝试绘制一个 Pandas DataFrame,并添加一条线来显示平均值和中位数。正如您在下面看到的,我为平均值添加了一条红线,但它没有显示出来。

如果我尝试在 5 处画一条绿线,它会在 x=190 处显示。所以显然 x 值被视为 0, 1, 2, ... 而不是 160, 165, 170, ...

如何绘制线条以使其 x 值与 x 轴的值匹配?

来自 Jupyter:

完整代码:

%matplotlib inline

from pandas import Series
import matplotlib.pyplot as plt

heights = Series(
    [165, 170, 195, 190, 170, 
     170, 185, 160, 170, 165, 
     185, 195, 185, 195, 200, 
     195, 185, 180, 185, 195],
    name='Heights'
)
freq = heights.value_counts().sort_index()


freq_frame = freq.to_frame()

mean = heights.mean()
median = heights.median()

freq_frame.plot.bar(legend=False)

plt.xlabel('Height (cm)')
plt.ylabel('Count')

plt.axvline(mean, color='r', linestyle='--')
plt.axvline(5, color='g', linestyle='--')

plt.show()

【问题讨论】:

  • 您可以发布您正在绘制的数据样本吗?
  • 完整来源,包括数据现已添加。

标签: python pandas matplotlib


【解决方案1】:

使用plt.bar(freq_frame.index,freq_frame['Heights']) 绘制条形图。然后这些条将位于freq_frame.index 位置。据我所知,Pandas 内置条形功能不允许指定条形的位置。

%matplotlib inline

from pandas import Series
import matplotlib.pyplot as plt

heights = Series(
    [165, 170, 195, 190, 170, 
     170, 185, 160, 170, 165, 
     185, 195, 185, 195, 200, 
     195, 185, 180, 185, 195],
    name='Heights'
)
freq = heights.value_counts().sort_index()

freq_frame = freq.to_frame()

mean = heights.mean()
median = heights.median()

plt.bar(freq_frame.index,freq_frame['Heights'],
        width=3,align='center')

plt.xlabel('Height (cm)')
plt.ylabel('Count')

plt.axvline(mean, color='r', linestyle='--')
plt.axvline(median, color='g', linestyle='--')

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    相关资源
    最近更新 更多