2017-10-19 137 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

相關問題