2016-01-16 11 views
8

Sto provando a tracciare un DataFrame di Pandas e aggiungere una linea per mostrare la media e la mediana. Come puoi vedere qui sotto, aggiungo una linea rossa per la media, ma non mostra.Riga media sopra il grafico a barre con panda e matplotlib

Se provo a disegnare una linea verde su 5, mostra x = 190. Quindi apparentemente i valori x sono trattati come 0, 1, 2, ... piuttosto che 160, 165, 170, ...

Come posso disegnare linee in modo che i loro valori x corrispondano a quelli dell'asse x?

Da Jupyter:

DataFrame plot

codice completo:

%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

inserire un campione dei dati che stai tramando? –

+0

La fonte completa, compresi i dati, è stata aggiunta ora. – oal

risposta

5

Usa plt.bar(freq_frame.index,freq_frame['Heights']) per tracciare la vostra grafico a barre. Quindi le barre saranno a freq_frame.index posizioni. La funzione bar in-build di Pandas non consente di specificare le posizioni delle barre, per quanto posso dire.

%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

Problemi correlati