小编oal*_*oal的帖子

条形图顶部的平均线与熊猫和matplotlib

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

如果我尝试在5处绘制绿线,则显示在x = 190处.所以显然x值被视为0,1,2 ......而不是160,165,170 ......

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

来自Jupyter:

DataFrame图

完整代码:

%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()
Run Code Online (Sandbox Code Playgroud)

python matplotlib pandas

9
推荐指数
1
解决办法
4309
查看次数

标签 统计

matplotlib ×1

pandas ×1

python ×1