Matplotlib: Pyplot By Example

Last updated:
Matplotlib: Pyplot By Example
Source

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Pyplot or Matplotlib? What's The difference?

Initialize sample data and imports

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0.0,100,50)
y = np.random.uniform(low=0,high=10,size=50)

Change size of Figure

After plotting, get a reference to the current figure and call set_size_inches(width,height):

plt.scatter(x,y)

# get reference to the current figure
fig = plt.gcf()

fig.set_size_inches(8,3)

plt.show() # not needed if matplotlib inline is enabled

set_size_inches Customized image with 8x3 inches.
(Default size is 6x4)

Save plot to file (instead of displaying it)

Use plt.savefig().

The image format is deduced from the extension ('png', 'jpg', 'svg', etc)

plt.scatter(x,y)

plt.savefig('out.png')

Multiple subplots in the same Figure

Call plt.subplots() to get a figure reference and individual Axes references (one for each subplot):

# passing 2,2 as parameters indicates that you will
# get 4 subplots (2 rows and 2 columns)
fig, axes = plt.subplots(2,2)

# just plot things on each individual axes
axes[0][0].scatter(x,y,c='red',marker='+')
axes[0][1].bar(x,y)
axes[1][0].scatter(x,y,marker='x')

axes[1][1].barh(x,y)
# optionally, add a title to this subplot only
axes[1][1].set_title('Plot 4')

plt.show() # not needed if matplotlib inline is enabled

pyplots-subplots Create a figure with 4 individual subplots using plt.subplots()

Set Figure Title and Font size for a Figure

Use Figure.suptitle()

plt.scatter(x,y)

# get reference to the current figure
fig = plt.gcf()

fig.suptitle('IMAGE TITLE HERE', fontsize=18)

plt.show() # not needed if matplotlib inline is enabled

set figure title pyplot suptitle() acceps parameters you would normally use in matplotlib.Text

Set Title and Font size for a single Axis

Similar to the above, but acts on a single Axis (useful if you have multiple suplots on the same Figure)

plt.scatter(x,y)

# get reference to the current axis
ax = plt.gca()

ax.set_title('title for this axis only', fontsize=20)

Change legend text and location

Use plt.legend() using the text and the location string (e.g. 'upper left' or 'lower right') as arguments.

plt.plot(x,y)

# when legend is called on the global pyplot
# namespace like this, it acts on the current axes
plt.legend(['Example legend'],loc='upper center')

plt.show() # not needed if matplotlib inline is enabled

set legend size Function legend() is available on pyplot but also on individual
Axes instances

Change tick label rotation

Use plt.xticks() or plt.yticks and set the rotation argument (degrees)

plt.plot(x,y)

# rotating labels on the xaxis
plt.xticks(rotation=60)
# y axis
plt.yticks(rotation=60)

plt.show() # not needed if matplotlib inline is enabled

rotate-ticks-on-pyplot You can change the label rotation for both the x-axis and the y-axis

Set Axis labels and fontsize

Use plt.xlabel() or plt.ylabel, using the same arguments that are accepted by plt.text().

plt.plot(x,y)

plt.xlabel('time (s)',color='red',fontsize=30)
plt.ylabel('temperature (C)', fontsize=15)

axis-labels-and-fontsize You can use any other arguments from plt.text() too.

Set y-axis, x-axis limits

plt.plot(x,y)

plt.ylim(-5,15)

plt.xlim(-30,130)

plt.show() # not needed if matplotlib inline is enabled

y-axis-limit-and-x-axis-limit Same data as before, with more room around it.

Add text to a plot

Label points in a plot

TODO this is called annotation by mplib

Set tick frequency

TODO    

References

Dialogue & Discussion