Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

Beginners Python Cheat Sheet Pcc Matplotlib

The document provides an overview of customizing plots using the Matplotlib library in Python, including methods for emphasizing points, using built-in styles, and creating various types of plots such as line graphs and scatter plots. It covers essential functionalities like adding titles, labels, and scaling axes, as well as saving plots and working with dates and times. Additionally, it explains how to create multiple plots in one figure and share axes between them.

Uploaded by

vertcodefreepdf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Beginners Python Cheat Sheet Pcc Matplotlib

The document provides an overview of customizing plots using the Matplotlib library in Python, including methods for emphasizing points, using built-in styles, and creating various types of plots such as line graphs and scatter plots. It covers essential functionalities like adding titles, labels, and scaling axes, as well as saving plots and working with dates and times. Additionally, it explains how to create multiple plots in one figure and share axes between them.

Uploaded by

vertcodefreepdf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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')
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)
--snip--
Installing Matplotlib You can see all available styles on your system. This can be done in
a terminal session.
Matplotlib runs on all systems, and you should be able to Removing axes
install it in one line. >>> import matplotlib.pyplot as plt You can customize or remove axes entirely. Here’s how to access
>>> plt.style.available each axis, and hide it.
Installing Matplotlib ['seaborn-dark', 'seaborn-darkgrid', ...
ax.get_xaxis().set_visible(False)
$ python -m pip install --user matplotlib Adding titles and labels, and scaling axes ax.get_yaxis().set_visible(False)
import matplotlib.pyplot as plt Setting a custom figure size
Line graphs and scatter plots
You can make your plot as big or small as you want by using the
Making a line graph x_values = list(range(1000)) figsize argument. The dpi argument is optional; if you don’t know
The fig object represents the entire figure, or collection of plots; ax squares = [x**2 for x in x_values] your system’s resolution you can omit the argument and adjust the
represents a single plot in the figure. This convention is used even figsize argument accordingly.
when there's only one plot in the figure. # Set overall style to use, and plot data.
fig, ax = plt.subplots(figsize=(10, 6),
import matplotlib.pyplot as plt plt.style.use('seaborn')
dpi=128)
fig, ax = plt.subplots()
x_values = [0, 1, 2, 3, 4, 5] ax.scatter(x_values, squares, s=10) Saving a plot
squares = [0, 1, 4, 9, 16, 25] 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
fig, ax = plt.subplots() ax.set_title('Square Numbers', fontsize=24) plt.savefig(). The bbox_inches argument reduces the amount of
ax.plot(x_values, squares) ax.set_xlabel('Value', fontsize=14) whitespace around the figure.
ax.set_ylabel('Square of Value', fontsize=14)
plt.savefig('squares.png', bbox_inches='tight')
plt.show()
# Set scale of axes, and size of tick labels.
Making a scatter plot ax.axis([0, 1100, 0, 1_100_000]) Online resources
scatter() takes a list of x and y values; the s=10 argument ax.tick_params(axis='both', labelsize=14) The matplotlib gallery and documentation are at
controls the size of each point. matplotlib.org/. Be sure to visit the examples, gallery, and
plt.show() pyplot links.
import matplotlib.pyplot as plt
Using a colormap
x_values = list(range(1000))
squares = [x**2 for x in x_values]
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
the color of each point is passed to the c argument, and the cmap A Hands-on, Project-Based
fig, ax = plt.subplots() argument specifies which colormap to use. Introduction to Programming
ax.scatter(x_values, squares, s=10)
ax.scatter(x_values, squares, c=squares, nostarch.com/pythoncrashcourse2e
plt.show()
cmap=plt.cm.Blues, s=10)
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') %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/2021', '%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, we 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')
dt(2020, 6, 21), dt(2020, 6, 22), fig, axs = plt.subplots(1, 2, sharey=True)
Generating the current date dt(2020, 6, 23), dt(2020, 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() fig, ax = plt.subplots() axs[1].set_title('Cubes')
date_string = today.strftime('%m/%d/%Y') ax.plot(dates, highs, c='red')
print(date_string) plt.show()
ax.set_title("Daily High Temps", fontsize=24)
Generating a specific date ax.set_ylabel("Temp (F)", fontsize=16)
You can also generate a datetime object for any date and time you x_axis = ax.get_xaxis()
want. The positional order of arguments is year, month, and day. x_axis.set_major_formatter(
The hour, minute, second, and microsecond arguments are optional. mdates.DateFormatter('%B %d %Y')
from datetime import datetime as dt )
fig.autofmt_xdate()
new_years = dt(2021, 1, 1)
fall_equinox = dt(year=2021, month=9, day=22) plt.show()
More cheat sheets available at
ehmatthes.github.io/pcc_2e/

You might also like