Matplotlib

Also refers to official cheatsheat here

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


Functional OOP
plt.xlabel() ax.set_xlabel()
plt.ylabel() ax.set_ylabel()
plt.xlim() ax.set_xlim()
plt.ylim() ax.set_ylim()
plt.title() ax.set_title()

1. General procedure for plotting

To create a 2D line plot, follow these general steps:

  1. Call the plt.figure() to create a new figure. (optional for %matplotlib inline)
  2. Generate a sequence of
    x
    values usually using linspace().
  3. Generate a sequence of
    y
    values usually by substitute the x values into a function.
  4. Input plt.plot(x, y, [format], **kwargs) where [format] is an (optional) format string, and **kwargs are (optional) keyword arguments specifying the line properties of the plot.
  5. Utilize plt functions to enhance the figure with features such as a title, legend, grid lines, etc.
  6. Input plt.show() to display the resulting figure (this step is optional in a Jupyter notebook).

2. Plots

Creating plots

Figure

Operator Description Documentation
fig = plt.figures() a container that contains all plot elements link

Axes

Operator Description Documentation
fig.add_axes()
a = fig.add_subplot(222)
Initializes subplot
A subplot is an axes on a grid system
row-col-num
link
fig, b = plt.subplots(nrows=3, nclos=2) Adds subplot link
ax = plt.subplots(2, 2) Creates subplot link

Plotting

1D Data

Operator Description Documentation
lines = plt.plot(x,y) Plot data connected by lines link
plt.scatter(x,y) Creates a scatterplot, unconnected data points link
plt.hist(x, y) Plots a histogram link
plt.fill_between(x,y,color='yellow') Fill area under/between plots link

Saving plots

Operator Description Documentation
plt.savefig('pic.png') Saves plot/figure to image link

Customization

Color

Operator Description Documentation
plt.plot(x, y, color='lightblue')
plt.plot(x, y, alpha = 0.4)
colors plot to color blue link
plt.colorbar(mappable, orientation='horizontal') mappable: the Image, Contourset etc to which colorbar applies link

Markers (see examples)

Operator Description Documentation
plt.plot(x, y, marker='*') adds * for every data point link
plt.scatter(x, y, marker='.') adds . for every data point see above

Lines

Operator Description Documentation
plt.plot(x, y, linewidth=2) Sets line width link
plt.plot(x, y, ls='solid') Sets linestyle, ls can be ommitted, see 2 below see above
plt.plot(x, y, ls='--') Sets linestyle, ls can be ommitted, see below see above
plt.plot(x,y,'--', x**2, y**2, '-.') Lines are '' and '_.' see above

Text

Operator Description Documentation
plt.text(1, 1,'Example Text',style='italic') Places text at coordinates 1/1 link
ax.annotate('some annotation', xy=(10, 10)) Annotate the point with coordinatesxy with text s link
plt.title(r'$delta_i=20$', fontsize=10) Mathtext link

Limits, Legends/Labels , Layout

Limits

Operator Description Documentation
plt.xlim(0, 7) Sets x-axis to display 0 - 7 link
plt.ylim(-0.5, 9) Sets y-axis to display -0.5 - 9 link
ax.set(xlim=[0, 7], ylim=[-0.5, 9])
ax.set_xlim(0, 7)
plt.axis('equal') Set the aspect ratio of the plot to 1

Legends/Labels

Operator Description Documentation
plt.title('just a title') Sets title of plot link
plt.xlabel('x-axis') Sets label next to x-axis link
plt.ylabel('y-axis') Sets label next to y-axis link
plt.legend(loc='best') No overlapping plot elements link

Ticks

Operator Description Documentation
plt.xticks(x, labels, rotation='vertical') link

3. Examples

Basics

import matplotlib.pyplot as plt

x = np.linspace(-2,2,200)
plt.plot(x, np.cos(x - 0), color='blue')         # specify color by name
plt.plot(x, np.cos(x - 1), color='g')            # short color code (rgbcmyk)
plt.plot(x, np.cos(x - 2), color='0.75')         # grayscale between 0 and 1
plt.plot(x, np.cos(x - 4), color=(1.0,0.2,0.3)); # RGB tuple, values 0 to 1

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

plt.plot(x, np.sin(x), '-g', label='sin(x)') # solid green line
plt.plot(x, np.cos(x), ':b', label='cos(x)') # dotted blue line

plt.title("A Sin/Cos Curve", fontsize=18)       # we can also specify the font size
plt.xlabel("x", fontsize=14)
plt.ylabel("sin(x)", fontsize=14)
plt.legend(fontsize=12)

plt.axis('equal');

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

plt.plot(x, y, '-vb', markersize=15, linewidth=4, markerfacecolor='orange', markeredgewidth=2)
plt.ylim(-1.2, 1.2);

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

plt.hist(data, bins=30, density=True, alpha=0.5, color='steelblue', edgecolor='none')
x = np.linspace(-4,4,100)
y = 1/(2*np.pi)**0.5 * np.exp(-x**2/2)
plt.plot(x,y,'b',alpha=0.8);

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 1000)

plt.plot(x, np.sin(x), 'r')
plt.plot(x, np.cos(x), 'g')
plt.fill_between(x, np.cos(x), np.sin(x), color='red', alpha=0.1);

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

import matplotlib.pyplot as plt

t = np.linspace(0, 2*np.pi, 64)
r = np.sin(t)
# plot in polar coordinates
plt.axes(projection='polar')
plt.plot(t+(r<0)*np.pi, np.abs(r), '-')

# Set ticks for polar coordinate
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2], ['0', '$\pi/2$', '$\pi$', '$3\pi/2$']);

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

Subplotting Examples

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 3)
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(2):
    for j in range(3):
        ax[i, j].text(0.5, 0.5, str((i, j)), fontsize=18, ha='center', va='center')