Plot a bar graph using DataFrame

Untitled Document This is to answer a student's question on WhatsApp

%matplotlib inline

import pandas as pd
import calendar

#data is from https://data.gov.sg/dataset/rainfall-monthly-total
df = pd.read_csv("data/rainfall-monthly-total.csv") 

# make the month column a datetime type
df.month = pd.to_datetime(df.month, errors='coerce')

# Create a new column that just has the year
df['date_year'] = df.month.dt.year

# Create a new column that just has the month
df['date_month']= df.month.dt.month

# Format the month number as a month name   
df['date_monthname']= df['date_month'].apply(lambda x: calendar.month_abbr[x])

# Extract only rainfall data for 2017
df_2017 = df[df.date_year==2017]

# Extract only two columns, the monthname and total rainfall
df_2017 = df_2017[["date_monthname", "total_rainfall"]]

# Set index to be the monthname, that will auto format the x-ticks as the month names
df_2017.set_index("date_monthname",inplace=True) 

# Plot a bar graph
df_2017.plot(kind="bar")


And this is the graph the code produces

Comments

Popular posts from this blog

How to create an organizational chart in your webpage using Google Organization Chart Tools