pandas 带有熊猫和 matplotlib 的条形图顶部的平均线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34828701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:31:10  来源:igfitidea点击:

Mean line on top of bar plot with pandas and matplotlib

pythonpandasmatplotlib

提问by oal

I'm trying to plot a Pandas DataFrame, and add a line to show the mean and median. As you can see below, I'm adding a red line for the mean, but it doesn't show.

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

If I try to draw a green line at 5, it shows at x=190. So apparently the x values are treated as 0, 1, 2, ... rather than 160, 165, 170, ...

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

How can I draw lines so that their x values match those of the x axis?

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

From Jupyter:

来自 Jupyter:

DataFrame plot

数据框图

Full code:

完整代码:

%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()

采纳答案by Sergey Antopolskiy

Use plt.bar(freq_frame.index,freq_frame['Heights'])to plot your bar plot. Then the bars will be at freq_frame.indexpositions. Pandas in-build bar function does not allow for specifying positions of the bars, as far as I can tell.

使用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()

bar plot

条形图