This notebook refers to the following blog post: Matplotlib: Pyplot by Example


In [1]:
import matplotlib

import matplotlib.pyplot as plt
import numpy as np

print(matplotlib.__version__,',', np.__version__)


2.1.0 , 1.16.2

In [2]:
# with this, you don't need to call plt.show()
%matplotlib inline

In [3]:
# for reproducibility
np.random.seed(42)

sample data generation


In [4]:
x = np.linspace(0.0,100,50)
y = np.random.uniform(low=0,high=10,size=50)

default arguments


In [5]:
plt.scatter(x,y)


Out[5]:
<matplotlib.collections.PathCollection at 0x7f096431ff60>

Change size of figure


In [6]:
# clear current figure
plt.clf()

plt.scatter(x,y)
fig = plt.gcf()
fig.set_size_inches(8,3)


Save plot to file


In [7]:
# clear current figure
plt.clf()

plt.scatter(x,y)

plt.savefig('out.png')


Multiple subplots in the same figure


In [8]:
# clear current figure
plt.clf()

fig, axes = plt.subplots(2,2)

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)
axes[1][1].set_title('Plot 4',size=14)

plt.subplots_adjust(wspace=0.25, hspace=0.25)

fig.set_size_inches(6,6)


<matplotlib.figure.Figure at 0x7f09642637b8>

In [9]:
# clear current figure
plt.clf()

fig, axes = plt.subplots(2,2)

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)
axes[1][1].set_title('Plot 4',size=14)

plt.subplots_adjust(wspace=0.50, hspace=1.0)

fig.set_size_inches(6,6)


<matplotlib.figure.Figure at 0x7f0964188be0>

Set figure title and font size


In [10]:
# clear current figure
plt.clf()

plt.scatter(x,y)

fig = plt.gcf()

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


Out[10]:
Text(0.5,0.98,'IMAGE TITLE HERE')

set figure title and font size for single axis


In [11]:
# clear current figure
plt.clf()

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)

plt.scatter(x,y)

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

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

plt.show()


Change legend text and location


In [12]:
# clear current figure
plt.clf()

plt.plot(x,y)
plt.legend(['Example legend'],loc='upper center')

plt.gcf().set_size_inches(7,5)


Change tick label rotation


In [13]:
# clear current figure
plt.clf()

plt.plot(x,y)

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

# y axis
plt.yticks(rotation=60)


Out[13]:
(array([-2.,  0.,  2.,  4.,  6.,  8., 10., 12.]),
 <a list of 8 Text yticklabel objects>)

Set axis labels and fontsize


In [14]:
plt.clf()
plt.plot(x,y)

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


Out[14]:
Text(0,0.5,'temperature (C)')

Set y-axis, x-axis limits


In [15]:
# clear current figure
plt.clf()

plt.plot(x,y)

plt.ylim(-5,15)

plt.xlim(-30,130)


Out[15]:
(-30, 130)

Set tick frequency


In [16]:
# clear current figure
plt.clf()

plt.plot(x,y)

# make the limits a bit larger so that we can see the results
plt.ylim(0,10)
plt.xlim(0,100)

# tell pyplot to write a x-axis tick every 5 units
plt.xticks(np.arange(0, 100, 5))
plt.show()


gridlines


In [17]:
import matplotlib.pyplot as plt
import numpy as np

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

plt.clf()
plt.gca().grid(True)

# select both y axis and x axis
gridlines = plt.gca().get_xgridlines() + plt.gca().get_ygridlines()

# choose line width
line_width = 0.7

for line in gridlines:
    line.set_linestyle(':')
    line.set_linewidth(line_width)
    
plt.plot(x,y)


Out[17]:
[<matplotlib.lines.Line2D at 0x7f096429e978>]

In [18]:
import matplotlib.pyplot as plt
import numpy as np

plt.clf()

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

plt.gca().grid(True, linewidth=1.0, linestyle=':')

plt.plot(x,y)


Out[18]:
[<matplotlib.lines.Line2D at 0x7f096424b940>]

In [19]:
def plot_value_labels(axis):

    rects = axis.patches

    # For each bar: Place a label
    for rect in rects:

        # Get X and Y placement of label from rect.
        y_value = rect.get_height()
        x_value = rect.get_x() + rect.get_width() / 2

        label = '{:.2f}'.format(y_value)
        
        # Vertical alignment for positive values
        va = 'bottom'

        # If value of bar is negative: Place label below bar
        if y_value < 0:
            # Invert space to place label below
            space *= -1
            # Vertically align label at top
            va = 'top'

        # Create annotation

        axis.annotate(label, (x_value, y_value), 
                      xytext=(0, 2), 
                      textcoords="offset points", 
                      ha='center', 
                      rotation=45, 
                      va=va)

In [20]:
import matplotlib.pyplot as plt
import numpy as np

# generate sample data
x = np.linspace(0.0,10,11)
y = np.random.uniform(low=0,high=6,size=11)

# plot bar plot
plt.bar(x,y)
plt.ylim(0,6)

# call the function we defined
plot_value_labels(plt.gca())

plt.show()


plot a histogram for values in an numpy array


In [21]:
import matplotlib.pyplot as plt
import numpy as np

# generate sample data following a normal distribution
values = np.random.normal(size=100)
# array([ 0.49671415, -0.1382643 ,  0.64768854,...

# see all examples in the API link
plt.hist(values,rwidth=0.9,bins=[-3,-2,-1,0,1,2,3])

plt.show()


string axis labels


In [22]:
np.random.seed(42)

xs = [1,2,3,4,5,6,7,8,9,10,11,12]
ys = np.random.normal(loc=3.0,size=12)
labels = ['jan','feb','mar','apr','may','jun','jul','aug','sept','oct','nov','dec']

plt.clf()
plt.bar(xs,ys)

# tell pyplot which labels correspond to which x values
plt.xticks(xs,labels)

plt.show()


horizontal bar plot


In [23]:
np.random.seed(42)

xs = [1,2,3,4,5,6,7,8,9,10,11,12]
ys = np.random.normal(loc=3.0,size=12)
labels = ['jan','feb','mar','apr','may','jun','jul','aug','sept','oct','nov','dec']

plt.clf()
plt.barh(xs,ys)

# tell pyplot which labels correspond to which x values
plt.yticks(xs,labels)

plt.show()


twin axes


In [24]:
plt.clf()

np.random.seed(10)

xs = [1,2,3,4,5,6,7,8,9,10,11,12]
ys_bars = np.random.normal(loc=3.0,size=12)
ys_lines = np.random.normal(loc=5.0,size=12,scale=0.5)

# this is the axis on the left
ax1=plt.gca()
ax1.bar(xs,ys_bars,color='green')

# order is important when setting ticks.
# Ticks must be set after the plot has been drawn
ax1.set_yticks(np.arange(0,11,1))
ax1.set_yticklabels(np.arange(0,11,1),color='green')

# create the 'twin' axis on the right
ax2=ax1.twinx()

# plot the same numbers but multiplied by 20
ax2.plot(xs,ys_lines*20,color='red')

# set the ticks and ticklabels for the twin axis
ax2.set_yticks(np.arange(0,131,10))
ax2.set_yticklabels(np.arange(0,131,10),color='red')

# set ticks for the x axis (bottom)
ax2.xaxis.set_ticks(xs)

# add grid (optional)
ax1.grid(True,linewidth=0.9,linestyle=':')
ax2.grid(True,linewidth=0.9,linestyle=':')

plt.gcf().set_size_inches(6,4)

plt.show()


align axis ticks and labels on twin axes


In [25]:
plt.clf()
np.random.seed(10)
xs = [1,2,3,4,5,6,7,8,9,10,11,12]
ys_bars = np.random.normal(loc=3.0,size=12)
ys_lines = np.random.normal(loc=5.0,size=12,scale=0.5)

# this is the axis on the left
ax1=plt.gca()
ax1.bar(xs,ys_bars,color='green')

num_ticks = 10

ax1.set_yticks(np.arange(0,10,1))
ax1.yaxis.set_major_locator(plt.LinearLocator(numticks=num_ticks))
ax1.set_yticklabels(['{:.0f}'.format(n) for n in ax1.get_yticks()],color='green')
# create the 'twin' axis on the right
ax2=ax1.twinx()

# plot the same numbers but multiplied by 20
ax2.plot(xs,ys_lines*20,color='red')
# set the ticks and ticklabels for the twin axis

ax2.set_yticks(np.arange(0,130,10))
ax2.yaxis.set_major_locator(plt.LinearLocator(numticks=num_ticks))
ax2.set_yticklabels(['{:.0f}'.format(n) for n in ax2.get_yticks()],color='red')

# set ticks for the x axis (bottom)
ax2.xaxis.set_ticks(xs)

# add grid (optional)
# ax1.tick_params(axis='y')

ax1.grid(True,linewidth=0.9,linestyle=':')
ax2.grid(True,linewidth=0.9,linestyle=':')

plt.gcf().set_size_inches(6,4)

plt.show()