如何使用Seaborn在X轴上绘制月份,在Y轴上绘制降雨?

时间:2020-09-01 23:40:42

标签: python data-visualization seaborn kaggle

我有一个数据集,来自Kaggle:https://www.kaggle.com/ravisane1/monthly-rainfall-data-india-of-a-century。我使用了melt通过执行

将月份从列转换为行
rain_data_by_month = rain_data.melt(id_vars=["State", "District","Year"], 
        var_name="Month", 
        value_name="Rainfall")

现在,我想在X轴上绘制月份,在Y轴上绘制总降雨量。所以我首先做了一个

rdf = rain_data_by_month.groupby(['Month'])['Rainfall'].sum().reset_index()

我如何才能像上面描述的那样绘制rdf?谢谢!

1 个答案:

答案 0 :(得分:1)

import pandas as pd
import seaborn as sns
import calendar

# load data
df = pd.read_csv('data/india_monthly_rainfall_data.csv')

# melt
dfm = df.melt(id_vars=["State", "District","Year"],  var_name="Month",  value_name="Rainfall")

# groupby sum
rdf = dfm.groupby(['Month'])['Rainfall'].sum().reset_index()

# ordered
rdf.Month = pd.Categorical(rdf.Month, categories=list(calendar.month_abbr)[1:], ordered=True)

# display(rdf)
Month     Rainfall
  Apr  2.15743e+06
  Aug  1.52092e+07
  Dec  6.44887e+05
  Feb  9.17824e+05
  Jan  7.38981e+05
  Jul  1.65285e+07
  Jun  1.02515e+07
  Mar  1.17930e+06
  May  4.09921e+06
  Nov  1.56662e+06
  Oct  4.33708e+06
  Sep  1.00620e+07

# plot
p = sns.barplot('Month', 'Rainfall', data=rdf)
p.set_ylabel('Rainfall (mm)')
p.set_title(f'1901 - 2002: Total Cumulative Monthly Rainfall')

enter image description here