Matplotlib Exercise 1

Imports


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

Line plot of sunspot data

Download the .txt data for the "Yearly mean total sunspot number [1700 - now]" from the SILSO website. Upload the file to the same directory as this notebook.


In [2]:
import os
assert os.path.isfile('yearssn.dat')

Use np.loadtxt to read the data into a NumPy array called data. Then create two new 1d NumPy arrays named years and ssc that have the sequence of year and sunspot counts.


In [3]:
data = np.loadtxt('yearssn.dat')
year = np.array(data[:,0])
ssc = np.array(data[:,1])

In [4]:
assert len(year)==315
assert year.dtype==np.dtype(float)
assert len(ssc)==315
assert ssc.dtype==np.dtype(float)

Make a line plot showing the sunspot count as a function of year.

  • Customize your plot to follow Tufte's principles of visualizations.
  • Adjust the aspect ratio/size so that the steepest slope in your plot is approximately 1.
  • Customize the box, grid, spines and ticks to match the requirements of this data.

In [5]:
plt.figure(figsize=(100,5)) # 9" x 6", default is 8" x 5.5"

plt.plot(year, ssc, '-')
plt.xlabel('Year')
plt.ylabel('Number of Sunspots')
#plt.ylim(-5,5)
plt.title('Sunspots since 1700'); # supress text output
plt.xlim(right = 2020)
plt.xticks(range(1700, 2000, 10))
max(year)


Out[5]:
2014.5

In [6]:
assert True # leave for grading

Describe the choices you have made in building this visualization and how they make it effective.

Choices influencing the plot:

  • Axes are labeled
  • Plot has a meaningful title
  • A lineplot was chosen since we would want to visualize changes over time
  • It's tough to fit the plot with the desired aspect ratio on a small window

Now make 4 subplots, one for each century in the data set. This approach works well for this dataset as it allows you to maintain mild slopes while limiting the overall width of the visualization. Perform similar customizations as above:

  • Customize your plot to follow Tufte's principles of visualizations.
  • Adjust the aspect ratio/size so that the steepest slope in your plot is approximately 1.
  • Customize the box, grid, spines and ticks to match the requirements of this data.

In [24]:
f, ax = plt.subplots(4, 1, sharex=False, sharey=True, figsize=(15,8))

for i in range(4):
    plt.sca(ax[i])
    plt.plot(year, ssc)
    plt.xticks(range(1700, 2100, 10))
    plt.xlim(1700 + i*100, 1700 + (i+1)*100)
    plt.ylabel('Number of Spots')
plt.tight_layout()
plt.xlabel("Year")


Out[24]:
<matplotlib.text.Text at 0x7f88d17a9240>

In [ ]:
assert True # leave for grading