2017-10-19 169 views
0

我有以下代码可以生成多年内给定月份的日降雨量条形图。使用read_excel,pandas,matplotlib将平均线添加到柱状图

df=pd.read_excel(("C:/Filepath/RainData.xls"), \ 
      sheetname=sheet,\ 
      header=0,\ 
      parse_cols="B:BD",\ 
      na_values='T') 

precip = df.loc[31, :] 


precipavg=((sum(precip[1:]))/(len(precip[1:]))) 
print(precipavg) 

df.head(0) 
fig,ax= plt.subplots() 

precip.plot(kind="bar",ax=ax, color='g',figsize=(15,7)) 

plt.minorticks_on() 
ax.tick_params(axis='x',which='minor',bottom='off') 
ax.set_xlabel("Year") 
ax.set_ylabel("Precipitation") 
ax.set_title((filename+" Precipitation"), fontsize=20) 

然后,我想在此条形图的顶部添加一条线,指示当月的降雨量。我已经使用上面的precipavg行来计算这个了。谢谢。

回答

0

您可以使用axhline如下:

import matplotlib.pyplot as plt 
import pandas as pd 
import numpy as np 

# dummy data 
df = pd.DataFrame(np.random.random(size=(20, 1)), columns=["rain"]) 

# your plot setup 
fig,ax= plt.subplots() 

df.plot(kind="bar", ax=ax, color='g',figsize=(15,7)) 

plt.minorticks_on() 
ax.tick_params(axis='x',which='minor',bottom='off') 
ax.set_xlabel("Year") 
ax.set_ylabel("Precipitation") 
ax.set_title(("Precipitation"), fontsize=20) 

# use axhline 
mean = df["rain"].mean() 
ax.axhline(mean) 

enter image description here