Beginners Python Cheat Sheet PCC Matplotlib BW

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 Emphasizing points
about any element of a plot can be modified. You can plot as much data as you want on one plot. Here we replot

Cheat Sheet - Using built-in styles


Matplotlib comes with a number of built-in styles, which you can use
with one additional line of code. The style must be specified before
the first and last points larger to emphasize them.
import matplotlib.pyplot as plt

Matplotlib you create the figure.


import matplotlib.pyplot as plt
x_values = list(range(1000))
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
visual representations. The Matplotlib library helps you plt.style.use('seaborn-v0_8')
fig, ax = plt.subplots() ax.scatter(x_values[0], squares[0], c='green',
make visually appealing representations of the data ax.scatter(x_values, squares, s=10) s=100)
you’re working with. Matplotlib is extremely flexible; ax.scatter(x_values[-1], squares[-1], c='red',
these examples will help you get started with a few plt.show() s=100)
simple visualizations.
Seeing available styles ax.set_title('Square Numbers', fontsize=24)
Many newer plotting libraries are wrappers around --snip--
You can see all available styles on your system. This can be done in
Matplotlib, and understanding Matplotlib will help you a terminal session.
use those libraries more effectively as well. Removing axes
>>> import matplotlib.pyplot as plt You can customize or remove axes entirely. Here’s how to access
>>> plt.style.available
Installing Matplotlib ['Solarize_Light2', '_classic_test_patch', ...
each axis, and hide it.

Installing Matplotlib with pip ax.get_xaxis().set_visible(False)


Adding titles and labels, and scaling axes ax.get_yaxis().set_visible(False)
$ python -m pip install --user matplotlib
import matplotlib.pyplot as plt 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
figsize argument. The dpi argument is optional; if you don’t know
Making a line graph squares = [x**2 for x in x_values] your system’s resolution you can omit the argument and adjust the
The fig object represents the entire figure, or collection of plots; ax figsize argument accordingly.
represents a single plot in the figure. This convention is used even # Set overall style to use, and plot data.
fig, ax = plt.subplots(figsize=(10, 6),
when there's only one plot in the figure. plt.style.use('seaborn-v0_8')
dpi=128)
fig, ax = plt.subplots()
import matplotlib.pyplot as plt
ax.scatter(x_values, squares, s=10) Saving a plot
x_values = [0, 1, 2, 3, 4, 5] The Matplotlib viewer has a save button, but you can also save
# Set chart title and label axes. your visualizations programmatically by replacing plt.show() with
squares = [0, 1, 4, 9, 16, 25]
ax.set_title('Square Numbers', fontsize=24) plt.savefig(). The bbox_inches argument reduces the amount of
ax.set_xlabel('Value', fontsize=14) whitespace around the figure.
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() Online resources
ax.axis([0, 1100, 0, 1_100_000])
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 matplotlib.org/. Be sure to visit the Examples, Tutorials, and
controls the size of each point. plt.show() User guide sections.
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 determine Python Crash Course
squares = [x**2 for x in x_values] the color of each point is passed to the c argument, and the cmap A Hands-on, Project-Based
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) ehmatthes.github.io/pcc_3e
cmap=plt.cm.Blues, s=10)
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. Datetime formatting arguments You can include as many individual graphs in one figure as
When you make multiple plots, you can emphasize The strptime() function generates a datetime object from a you want.
relationships in the data. For example you can fill the space string, and the strftime() method generates a formatted string
Sharing an x-axis
between two sets of data. 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
exactly as you need to.
Plotting two sets of data two separate graphs that share a common x-axis. The plt.
Here we use ax.scatter() twice to plot square numbers and %A Weekday name, such as Monday subplots() function returns a figure object and a tuple of axes.
cubes on the same figure. %B Month name, such as January Each set of axes corresponds to a separate plot in the figure.
%m Month, as a number (01 to 12) The first two arguments control the number of rows and columns
import matplotlib.pyplot as plt %d Day of the month, as a number (01 to 31) generated in the figure.
%Y Four-digit year, such as 2021 import matplotlib.pyplot as plt
x_values = list(range(11)) %y Two-digit year, such as 21
squares = [x**2 for x in x_values] %H Hour, in 24-hour format (00 to 23)
cubes = [x**3 for x in x_values] x_values = list(range(11))
%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-v0_8') %M Minutes (00 to 59)
fig, ax = plt.subplots() %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
ax.scatter(x_values, cubes, c='red', s=10) axs[0].scatter(x_values, squares)
new_years = dt.strptime('1/1/2023', '%m/%d/%Y') axs[0].set_title('Squares')
plt.show() Converting a datetime object to a string axs[1].scatter(x_values, cubes, c='red')
Filling the space between data sets ny_string = new_years.strftime('%B %d, %Y') axs[1].set_title('Cubes')
The fill_between() method fills the space between two data sets. print(ny_string)
It takes a series of x-values and two series of y-values. It also takes plt.show()
a facecolor to use for the fill, and an optional alpha argument that Plotting high temperatures
controls the color’s transparency. The following code creates a list of dates and a corresponding list of Sharing a y-axis
high temperatures. It then plots the high temperatures, with the date To share a y-axis, use the sharey=True argument.
ax.fill_between(x_values, cubes, squares, labels displayed in a specific format.
facecolor='blue', alpha=0.25) import matplotlib.pyplot as plt
from datetime import datetime as dt
x_values = list(range(11))
Working with dates and times import matplotlib.pyplot as plt squares = [x**2 for x in x_values]
Many interesting data sets have a date or time as the x 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. dates = [ plt.style.use('seaborn-v0_8')
dt(2023, 6, 21), dt(2023, 6, 22), fig, axs = plt.subplots(1, 2, sharey=True)
Generating the current date dt(2023, 6, 23), dt(2023, 6, 24),
The datetime.now() function returns a datetime object ] axs[0].scatter(x_values, squares)
representing the current date and time.
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() plt.style.use('seaborn-v0_8') 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 optional. x_axis.set_major_formatter(
from datetime import datetime as dt mdates.DateFormatter('%B %d %Y')
)
new_years = dt(2023, 1, 1) fig.autofmt_xdate()
fall_equinox = dt(year=2023, month=9, day=22) Weekly posts about all things Python
plt.show()
mostlypython.substack.com

You might also like