Beginners Python Cheat Sheet PCC Matplotlib PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Beginner's Python

Customizing Plots Customizing plots (cont.)


Plots can be customized in a wide variety of ways. Just
about any element of a plot can be customized. Emphasizing points

Cheat Sheet –
You can plot as much data as you want on one plot. Here we re-
Using built-in styles plot the first and last points larger to emphasize them.
Matplotlib comes with a number of built-in styles, which you can
import matplotlib.pyplot as plt

Matplotlib
use with one additional line. The style must be specified before you
create the figure.
x_values = list(range(1000))
import matplotlib.pyplot as plt squares = [x**2 for x in x_values]

x_values = list(range(1000)) fig, ax = plt.subplots()


What is Matplotlib? squares = [x**2 for x in x_values] ax.scatter(x_values, squares, c=squares,
cmap=plt.cm.Blues, s=10)
Data visualization involves exploring data through plt.style.use('seaborn')
visual representations. The matplotlib package fig, ax = plt.subplots() ax.scatter(x_values[0], squares[0], c='green',
helps you make visually appealing representations of ax.scatter(x_values, squares, s=10) s=100)
the data you’re working with. Matplotlib is extremely plt.show() ax.scatter(x_values[-1], squares[-1], c='red',
flexible; these examples will help you get started with s=100)
Seeing available styles
a few simple visualizations. You can see all available styles on your system. This can be done
in a terminal session. ax.set_title('Square Numbers', fontsize=24)
--snip--
Installing Matplotlib >>> import matplotlib.pyplot as plt
Matplotlib runs on all systems, and you should be able to >>> plt.style.available Removing axes
install it in one line. ['seaborn-dark', 'seaborn-darkgrid', ... You can customize or remove axes entirely. Here’s how to access
each axis, and hide it.
Installing Matplotlib Adding titles and labels, and scaling axes
ax.get_xaxis().set_visible(False)
$ python -m pip install --user matplotlib import matplotlib.pyplot as plt ax.get_yaxis().set_visible(False)
Setting a custom figure size
Line graphs and scatter plots x_values = list(range(1000))
You can make your plot as big or small as you want by using the
squares = [x**2 for x in x_values] figsize argument. The dpi argument is optional; if you don’t
Making a line graph know your system’s resolution you can omit the argument and
fig represents the entire figure, or collection of plots; ax # Set overall style to use, and plot data. adjust the figsize argument accordingly.
represents a single plot in the figure. plt.style.use('seaborn')
fig, ax = plt.subplots() fig, ax = plt.subplots(figsize=(10, 6),
import matplotlib.pyplot as plt dpi=128)
ax.scatter(x_values, squares, s=10)
x_values = [0, 1, 2, 3, 4, 5] Saving a plot
squares = [0, 1, 4, 9, 16, 25] # Set chart title and label axes. The Matplotlib viewer has a save button, but you can also save
ax.set_title('Square Numbers', fontsize=24) your visualizations programmatically by replacing plt.show() with
ax.set_xlabel('Value', fontsize=14) plt.savefig().
fig, ax = plt.subplots()
ax.set_ylabel('Square of Value', fontsize=14)
ax.plot(x_values, squares) plt.savefig('squares.png', bbox_inches='tight')
# Set scale of axes, and size of tick labels.
plt.show()
ax.axis([0, 1100, 0, 1_100_000]) Online resources
Making a scatter plot ax.tick_params(axis='both', labelsize=14) The matplotlib gallery and documentation are at
scatter() takes a list of x and y values; the s=10 argument https://matplotlib.org/. Be sure to visit the examples, gallery,
controls the size of each point. plt.show() and pyplot links.
import matplotlib.pyplot as plt Using a colormap
x_values = list(range(1000))
A colormap varies the point colors from one shade to another,
based on a certain value for each point. The value used to
Python Crash Course
squares = [x**2 for x in x_values] determine the color of each point is passed to the c argument, and A Hands-On, Project-Based
the cmap argument specifies which colormap to use.
Introduction to Programming
fig, ax = plt.subplots() ax.scatter(x_values, squares, c=squares,
ax.scatter(x_values, squares, s=10) cmap=plt.cm.Blues, s=10) nostarch.com/pythoncrashcourse2e
plt.show()
Multiple plots Working with dates and times (cont.) Multiple plots in one figure
You can make as many plots as you want on one figure. You can include as many individual graphs in one figure as
When you make multiple plots, you can emphasize Datetime formatting arguments you want.
The strptime() function generates a datetime object from a
relationships in the data. For example you can fill the space
between two sets of data.
string, and the strftime() method generates a formatted string Sharing an x-axis
from a datetime object. The following codes let you work with dates The following code plots a set of squares and a set of cubes on
Plotting two sets of data exactly as you need to. two separate graphs that share a common x-axis.
Here we use ax.scatter() twice to plot square numbers and The plt.subplots() function returns a figure object and a tuple
%A Weekday name, such as Monday
cubes on the same figure. of axes. Each set of axes corresponds to a separate plot in the
%B Month name, such as January figure. The first two arguments control the number of rows and
import matplotlib.pyplot as plt %m Month, as a number (01 to 12) columns generated in the figure.
%d Day of the month, as a number (01 to 31)
%Y Four-digit year, such as 2016 import matplotlib.pyplot as plt
x_values = list(range(11))
squares = [x**2 for x in x_values] %y Two-digit year, such as 16
%H Hour, in 24-hour format (00 to 23) x_values = list(range(11))
cubes = [x**3 for x in x_values]
%I Hour, in 12-hour format (01 to 12) squares = [x**2 for x in x_values]
%p AM or PM cubes = [x**3 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots() %M Minutes (00 to 59)
%S Seconds (00 to 61) fig, axs = plt.subplots(2, 1, sharex=True)
ax.scatter(x_values, squares, c='blue', s=10)
Converting a string to a datetime object axs[0].scatter(x_values, squares)
ax.scatter(x_values, cubes, c='red', s=10)
axs[0].set_title('Squares')
new_years = dt.strptime('1/1/2019', '%m/%d/%Y')
plt.show()
Converting a datetime object to a string axs[1].scatter(x_values, cubes, c='red')
Filling the space between data sets axs[1].set_title('Cubes')
The fill_between() method fills the space between two data ny_string = new_years.strftime('%B %d, %Y')
sets. It takes a series of x-values and two series of y-values. It also print(ny_string) plt.show()
takes a facecolor to use for the fill, and an optional alpha
argument that controls the color’s transparency. Plotting high temperatures Sharing a y-axis
The following code creates a list of dates and a corresponding list To share a y-axis, we use the sharey=True argument.
ax.fill_between(x_values, cubes, squares, of high temperatures. It then plots the high temperatures, with the
facecolor='blue', alpha=0.25) date labels displayed in a specific format. import matplotlib.pyplot as plt
from datetime import datetime as dt
x_values = list(range(11))
Working with dates and times squares = [x**2 for x in x_values]
Many interesting data sets have a date or time as the x- import matplotlib.pyplot as plt
from matplotlib import dates as mdates cubes = [x**3 for x in x_values]
value. Python’s datetime module helps you work with this
kind of data. plt.style.use('seaborn')
dates = [
fig, axs = plt.subplots(1, 2, sharey=True)
Generating the current date dt(2019, 6, 21), dt(2019, 6, 22),
The datetime.now() function returns a datetime object dt(2019, 6, 23), dt(2019, 6, 24),
representing the current date and time. ] axs[0].scatter(x_values, squares)
axs[0].set_title('Squares')
from datetime import datetime as dt
highs = [56, 57, 57, 64]
axs[1].scatter(x_values, cubes, c='red')
today = dt.now() axs[1].set_title('Cubes')
date_string = today.strftime('%m/%d/%Y') fig, ax = plt.subplots()
print(date_string) ax.plot(dates, highs, c='red')
plt.show()
Generating a specific date ax.set_title("Daily High Temps", fontsize=24)
You can also generate a datetime object for any date and time you ax.set_ylabel("Temp (F)", fontsize=16)
want. The positional order of arguments is year, month, and day. x_axis = ax.get_xaxis()
The hour, minute, second, and microsecond arguments are x_axis.set_major_formatter(
optional.
mdates.DateFormatter('%B %d %Y')
from datetime import datetime as dt )
fig.autofmt_xdate()
new_years = dt(2019, 1, 1) More cheat sheets available at
fall_equinox = dt(year=2019, month=9, day=22) plt.show() ehmatthes.github.io/pcc_2e/

You might also like