This worksheet focuses on Matplotlib as covered in Lectures 25--26. It also makes use of the material on Julia sets in the asynchronous Lecture 24.
These things might be helpful while working on the problems. Remember that for worksheets, we don't strictly limit what resources you can consult, so these are only suggestions.
For the purposes of this worksheet, the online text by VanderPlas is the main place to look if you want to do something in matplotlib and don't remember how, or if the exact feature that is required was not demonstrated in lecture.
However, here are a couple of features that will definitely be useful to keep in mind:
It's a good idea to work on this worksheet in the Jupyter/ipython notebook environment. For most people, these commands in the shell will install the prerequisite modules and launch a browser with the notebook environment:
# Install stuff
python3 -m pip install notebook numpy matplotlib
# .. now you should cd to where you want to work ..
# Launch notebook
python3 -m notebook
Another option is to use Google Colab which has matplotlib pre-installed. You can do everything there if you like, but steps that involve files (reading or writing) are a little simpler if you use matplotlib installed on your own computer. There is a section at the end of this document with tips for how to read and write files in Colab.
I suggest starting every matplotlib notebook with:
import matplotlib.pyplot as plt
import numpy as np
When matplotlib expects you to specify color, you can use a string name like "red"
or "orange"
as we did in lecture (and there are lots of named colors you can use), but you can specify a color in several other ways. One of the easiest and most flexible is to use HTML-style hex colors, in the format "#C0FFEE"
. Here, the six hex digits split into pairs to give the red, green, and blue components, which in this case are 0xC0 = 192
red, 0xFF = 255
green, and 0xEE = 238
blue. You can use an online color picker to choose a color visually and see the hex codes.
The default figure size used by matplotlib might be a little small (though it depends on your OS, screen resolution, browser, and notebook environment). If you find that to be the case, I recommend adjusting the output plot size by starting your figure with this command:
# Use a resolution expected to result in a figure 8 inches wide, 6 tall, on a display that
# has 120 pixels per inch
plt.figure(figsize=(8,6),dpi=120)
Matplotlib is not a perfect tool for making graphs of functions (because it doesn't know about continuity, domain, etc.; it just plots data point). But it can be used for this. To get started working on your own with matplotlib, make plots of the following functions according to the given specifications:
A single figure shows a range of 1 to 20 on the x axis and 0 to 600 on the y axis. The graphs of four functions are shown:
(In these expressions, $\log(x)$ means the natural logarithm, which is the usual mathematical convention and is consistent with the name in numpy. The same function is sometimes called $\ln(x)$.)
The x axis should be labeled "x", and the y axis should be labeled "Instructions executed".
The plot should have a legend showing which function corresponds to each color and line style.
You should use 50 sample points when computing the arrays for these plots, and for the plot of $f(x) = 15x$, the individual data points should be marked with dots (in addition to the line running through them).
The plot should have an overall title "Several functions".
Every atom has a nucleus that contains protons and neutrons. The number of protons determines what chemical element the atom corresponds to, e.g. a hydrogen nucleus has one proton, a helium nucleus has two, and a carbon nucleus has 6. My favorite element, tin, has nuclei with 50 protons.
The number of neutrons can vary from one atom of an element to another. Most carbon atoms have 6 neutrons, but some have 7 or 8. These are called isotopes of carbon. The 6- and 7-neutron carbon atoms are stable (they don't break apart on their own), while the 8-neutron ones are unstable: in time, such atoms undergo radioactive decay and turn into another element.
The term nuclides refers to all isotopes of all elements. That is, it refers to all the possible nuclei that exist. While you're probably familiar with the periodic table containing about 115 elements, there are thousands of nuclides.
Using data from the International Atomic Energy Agency API, I've constructed a CSV file containing data about 2935 nuclides. I selected the ones that are either stable or have a limited degree of instability (each nucleus typically surviving for at least 1 millisecond). Here's a link to the file:
There are five columns in this file:
symbol
: The two-letter symbol for the corresponding chemical element (str)neutrons
: The number of neutrons (int)protons
: The number of protons (int)instability
: A number between 0.0 and 1.0 which measures how unstable the nuclide is. (See below if you want a more detailed explanation.) A value of 0.0 means stable or very slow decay; 1.0 means fast decay. (float)abundance
: Among all nuclides with this number of protons, what percentage have this number of neutrons. Between 0.0 and 100.0. (float)Make a scatter plot in which
When you're done, you'll have created something similar to the live web-based visualization system on the IAEA Live Chart of Nuclides. If you want, you can use that site as a reference for certain aspects of what your plot will look like. (That site colors points by type of decay by default, but can be configured to color by stability using the menus.)
You might recall in lecture 26 I wrote some code to load a CSV file into a dictionary mapping column names to arrays of values, and that was helpful for making scatter plots. You'll want something similar for this problem, so here is a polished version of that code you can use. You just call csv_columns(fn)
with fn
replaced by a filename to get such a dictionary as the return value.
import numpy as np
import csv
import collections
def best_guess_type_conv(L):
"""
Make a guess about the type of values represented
by the list of strings L. Convert to integers if
possible, floats if not, and keep as strings if
both of those fail.
"""
try:
V = [float(x) for x in L]
except ValueError:
return L[:] # not floats -> keep as str
W = [int(x) for x in V]
if V==W:
# Converting to int did not change any
# values; so they seem to be integers.
return W
return V
def csv_columns(fn):
"""
Read a CSV file with headers and return
a dictionary whose keys are column names
and whose values are numpy arrays
"""
columns_raw = collections.defaultdict(list)
with open(fn,"r",newline="",encoding="UTF-8") as fp:
reader = csv.DictReader(fp)
for row in reader:
for field in row:
x = row[field]
columns_raw[field].append(x)
columns = dict()
for colname, coldata in columns_raw.items():
V = best_guess_type_conv( coldata )
if isinstance(V[0],str):
columns[colname] = V
else:
columns[colname] = np.array(V)
return columns
You don't need to read this section. It contains more detail about what the instability measurements in nuclides.csv
really mean.
The column instability
contains a number $x$ that is computed from the half-life $\lambda$ of the nuclide (measured in seconds) as follows:
For example, if the nuclide is stable, then $\lambda = +\infty$ and $x=0$. But if it is very unstable, $\lambda$ will be near $0$ and so $x$ will be close to $1$.
Recording $x$ in the data file rather than $\lambda$ makes it a little easier to construct a scatter plot.
In Lecture 24 we worked on a notebook for making pictures of Julia sets. We ended up with nice pictures like this one:
But they were created by passing numpy
arrays directly to Pillow, so they don't come with axes or labels or any information about what part of the complex plane you're seeing.
Adapt the code from that notebook to generate an image of a Julia set and then display it in a matplotlib figure using plt.imshow()
. The desired output would look something like this:
You need to pass the extent
keyword argument to imshow
to tell it the limits of the x and y axes. Check out Section 4.04 of VanderPlas for details.
I think you'll have the easiest time working on MCS 275 problems related to matplotlib if you install the notebook environment and matplotlib module locally.
However, as I mentioned in lecture, you don't need to install matplotlib locally in order to complete MCS 275 assignments. It is pre-installed in Google Colab, allowing you to use matplotlib in a notebook interface without installing anything.
In whatever way you use matplotlib, you might need to save plots or load data from a file. Working with files is easy if you install matploblib locally, but requires an extra step in Colab.
If you run Python code that writes to a file in Colab, the file will be saved to a temporary location (in Colab, not on your computer) that you can't directly access from outside the notebook interface. From within your notebook, it will look like the file exists and can be read back again. But once you exit colab, it will be gone.
To read and write files in Colab that are persistent and accessible outside of a single notebook instance, you can connect a Colab notebook to your google drive (associated to your uic.edu account, the same one that you use Colab with). Here is a demonstration of how to do it. This code won't work locally or in jupyter, but will work in Colab:
# Import the module to link to google drive
from google.colab import drive
# Make it so "/drive" refers to my google drive
# This will prompt you to allow google colab to access google drive, and ask
# you which google account you want to link.
drive.mount("/drive")
After running that cell in Colab, your entire google drive will appear as part of the filesystem accessible to the Python code you run in Colab, in a directory called "/drive/My Drive". You can upload data to drive and then work with it in a Colab notebook, or you can save results to files in Colab and then download them to your computer using Google drive.
By default, the notebooks you create in Colab are stored in a folder inside your google drive called "Colab Notebooks". In Colab, you would use that path "/drive/My Drive/Colab Notebooks" to access that folder. So, after calling drive.mount("/drive")
in a notebook, a typical way to create a file in the same directory as the notebook that you can later download using Google drive would be:
# create a CSV file in colab that I can later download from google drive
import csv
data = [ ("n","n**2"), (1,1), (2,4), (3,9), (4,16) ]
with open("/drive/My Drive/Colab Notebooks/squares.csv","wt",newline="") as outfile:
writer = csv.writer(outfile)
for row in data:
writer.writerow(row)
Reading from files is similar; you need to mount google drive and then read from a filename that begins with /drive/My Drive/Colab Notebooks/
.