【问题标题】:Adding avg line to bar plot using read_excel, pandas, matplotlib [duplicate]使用 read_excel、pandas、matplotlib 将平均线添加到条形图 [重复]
【发布时间】:2018-03-31 10:05:22
【问题描述】:

我有以下代码来生成多年来给定月份的每日降雨量条形图。

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 行计算了这个。谢谢。

【问题讨论】:

    标签: python excel pandas matplotlib


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多