2016-01-16 302 views
8

我试图绘制一个熊猫数据框,并添加一行来显示平均值和中位数。正如你在下面看到的,我为平均值添加了一条红线,但没有显示。用熊猫和matplotlib绘制条形图的平均线

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

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

从Jupyter:

DataFrame plot

全码:

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

愿你发布你绘制数据的样本? –

+0

包括数据在内的完整源代码已添加。 – oal

回答

5

使用plt.bar(freq_frame.index,freq_frame['Heights'])绘制的柱状图。然后酒吧将在freq_frame.index职位。就我所知,大熊猫的内置条形函数不允许指定条形的位置。

%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