For π€― inspiration + π©βπ» code, check out the Python Graph Gallery
Basic Setup
Every figure in this course starts with one import.
import matplotlib.pyplot as pltThe commands below all act on βthe current figureβ. You make a figure, add things to it, and then show it. You do not have to keep track of an object in between.
Sample Data
The examples use Toolik Lake monthly mean air temperatures, the same table Day 7 plots.
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
temps = [-22.89, -20.70, -20.69, -11.76, -0.80, 8.59,
11.22, 7.23, -0.11, -10.54, -18.34, -21.44]Sizing the Figure
figsize is given in inches, as width then height. Start a figure with it whenever the default proportions do not suit the data.
plt.figure(figsize=(10, 5))Common Plot Types
Line plot
Use a line when the x values have a meaningful order, such as time.
plt.plot(months, temps)Scatter plot
Use a scatter when the x values have no order, and each point is an independent observation.
plt.scatter(bill_length, bill_depth)Bar plot
plt.bar(months, temps) # vertical bars
plt.barh(months, temps) # horizontal bars, easier to read with long category namesHistogram
A histogram takes one sequence of numbers and shows how they are distributed. The bar heights are counts.
plt.hist(temps, bins=10)Labelling a Figure
An unlabelled figure is not finished. Axis labels should give units.
plt.xlabel('Month')
plt.ylabel('Mean air temperature (deg C)')
plt.title('Toolik Lake monthly mean air temperature')Legends
Give each series a label= when you draw it, then call legend() once for the whole figure.
plt.plot(months, early_temps, label='1988 to 2002')
plt.plot(months, late_temps, label='2003 to 2018')
plt.legend()Rotating Tick Labels
When category names collide along the x axis, rotate them. ha='right' sets the horizontal alignment so that the rotated labels line up under their ticks.
plt.xticks(rotation=45, ha='right')Fixing Crowded Layouts
tight_layout() adjusts the spacing so that labels are not cut off. Call it last, just before showing the figure.
plt.tight_layout()Showing and Saving
plt.show() # display the figure
plt.savefig('my_plot.png', dpi=300) # save it to a fileCall savefig() before show(). Showing a figure clears it.
A Complete Example
import matplotlib.pyplot as plt
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
temps = [-22.89, -20.70, -20.69, -11.76, -0.80, 8.59,
11.22, 7.23, -0.11, -10.54, -18.34, -21.44]
plt.figure(figsize=(10, 5))
plt.bar(months, temps)
plt.xlabel('Month')
plt.ylabel('Mean air temperature (deg C)')
plt.title('Toolik Lake monthly mean air temperature')
plt.tight_layout()
plt.show()Plotting from a pandas Series
A grouped result is a Series: its index holds the labels and its values hold the numbers. Pass those two pieces to any plotting command.
monthly = df.groupby('month')['temp_c'].mean()
plt.figure(figsize=(10, 5))
plt.bar(monthly.index, monthly.values)
plt.xlabel('Month')
plt.ylabel('Mean air temperature (deg C)')
plt.tight_layout()
plt.show()Matplotlib and Seaborn
These are the only two plotting libraries this course uses. Seaborn draws the figure for you from a DataFrame, and matplotlib gives you the commands to label and size the result. The two work on the same figure, so you can call plt.xlabel() after sns.scatterplot().
See the seaborn cheatsheet, the bar plot cheatsheet, and the matplotlib PDF reference.