Skip to content

Instantly share code, notes, and snippets.

@brettpetch
Last active December 1, 2019 23:17
Show Gist options
  • Save brettpetch/f793cc8b5f7824903ecf6fcc74ff71e4 to your computer and use it in GitHub Desktop.
Save brettpetch/f793cc8b5f7824903ecf6fcc74ff71e4 to your computer and use it in GitHub Desktop.
How to graph from a pandas dataframe
import pandas as pd # Use pandas instead to map the data easily
import matplotlib.pyplot as plt # Use Matplotlib PyPlot to create graph
import numpy as np # Use Numpy to take mean
def all_temp_plot(filename="London_mean_etr_max_etr_min.csv"):
# Note: This will not drop years with incomplete datsets.
# Read CSV, but only 3 columns because no one cares about the other ones
# then group years, then take mean of months and append it to a new column in a new dataframe.
df = pd.read_csv(filename, delimiter=',', usecols=[0, 1, 2],
names=['Year', 'Month', 'Temperature']).groupby('Year').agg(
Average_Temperature=pd.NamedAgg(column='Temperature', aggfunc=np.mean))
# reset the index to have a proper record of records {we just dropped values to do mean}
df.reset_index(inplace=True, drop=False)
# rename columns to a human-readable form
df.columns = ['Year', 'Average Temperature']
# plot the thing
df.plot(kind='line', x='Year', y='Average Temperature',
color='red', title='Average Annual Temperature in London, Ontario')
# show the plot
plt.show()
all_temp_plot()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment