Imagine we are keeping track of the amount of medication a patient takes over a year:
import matplotlib.pyplot as plt
pills = [10, 12, 13, 15, 12, 11,
9, 8, 8, 10, 11, 12
]
plt.plot(pills) # This prepares a plot
plt.show() # Show the plot that was created
Since we have not given any explicit x-axis values, pyplot
has used the index of our list for that purpose.
Note: Pyplot
internally keeps track of state of the plot. You as the user only get to see it once you call the show()
function. This way of programming is called imperative. There is also a different approach to things, which is called object oriented which is used in the underlying workings of matplotlib
. For clarity reasons we will show pyplot first and then expand upon that a bit later. To help with understanding, imagine you want to have a cake. Imperative style is like calling a baker and describing how you want your cake to look like. Object oriented style is like ordering the ingredients and then modifying the soon-to-be-cake yourself until it looks like you want it.
A simple way to plot something with specific x-values is to have separate lists of x and y values. The x-values do not need to be numbers, category names work equally as well. Try:
import matplotlib.pyplot as plt
months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
pills = [10, 12, 13, 15, 12, 11,
9, 8, 8, 10, 11, 12
]
plt.plot(months, pills)
plt.show()
We now have a very simple plot, but it is lacking a few things that we expect. Let us add some basic things like labels, a title and maybe a better scale for the y-axis.
import matplotlib.pyplot as plt
import numpy as np
months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
pills = [10, 12, 13, 15, 12, 11,
9, 8, 8, 10, 11, 12
]
plt.plot(months, pills)
# First let's put in the overall decorations
plt.xlabel("Month")
plt.ylabel("#")
plt.title("Amount of pills per month")
# We want our y-axis to start at 7 and go up to 16 with a resolution of 1
amt_pills_marks = np.arange(7,17,1)
plt.yticks(amt_pills_marks)
plt.show()
For the viewers convenience we also want to add horizontal lines to indicate the minimum and maximum values of the pills amount.
import matplotlib.pyplot as plt
import numpy as np
months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
pills = [10, 12, 13, 15, 12, 11,
9, 8, 8, 10, 11, 12
]
plt.plot(months, pills)
# First let's put in the overall decorations
plt.xlabel("Month")
plt.ylabel("#")
plt.title("Amount of pills per month")
# We want our y-axis to start at 7 and go up to 16 with a resolution of 1
amt_pills_marks = np.arange(7,17,1)
plt.yticks(amt_pills_marks)
# Add the lines for the lowest and highest pills amount
marker_lines = [min(pills), max(pills)]
plt.hlines(
y=marker_lines,
xmin=months[0],
xmax=months[-1],
linestyles="dotted",
colors="lightgray"
)
plt.show()