Examples

Plot

Basic

../../_images/plot.svg

[source: plot.py]


import numpy             as np
import matplotlib.pyplot as plt

plt.style.use(['goose','goose-latex'])

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

fig,ax = plt.subplots()

ax.plot(x,np.sin(x)         ,label=r'$\sin \big( x \big)$')
ax.plot(x,np.sin(x-np.pi/4.),label=r'$\sin \big( x - \tfrac{\pi}{4} \big)$')

ax.set_title('Simple plot')

ax.xaxis.set_ticklabels(['0',r'$\pi$',r'$2\pi$'])
ax.xaxis.set_ticks([0,np.pi,2*np.pi])
ax.yaxis.set_ticks([-1,0,1])

ax.legend(loc='upper right')

ax.set_xlim([0,2*np.pi])

ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')

plt.savefig('plot.svg')
plt.show()

Subplot

../../_images/subplot.svg

[source: subplot.py]


import numpy             as np
import matplotlib.pyplot as plt

plt.style.use(['goose','goose-latex'])

# --- some data ---

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

# --- open figure with 2 subplots ---

fig, axes = plt.subplots(ncols=2, figsize=(18,6))

ax1 = axes[0]
ax2 = axes[1]

# --- first subplot ---

ax1.plot(x,np.sin(x)         ,label=r'$\sin \big( x \big)$')
ax1.plot(x,np.sin(x-np.pi/4.),label=r'$\sin \big( x - \tfrac{\pi}{4} \big)$')

ax1.set_title('First subplot')

ax1.xaxis.set_ticklabels(['0',r'$\pi$',r'$2\pi$'])
ax1.xaxis.set_ticks([0,np.pi,2*np.pi])
ax1.yaxis.set_ticks([-1,0,1])

ax1.legend(loc='upper right')

ax1.set_xlim([0,2*np.pi])

ax1.set_xlabel(r'$x$')
ax1.set_ylabel(r'$y$')

# --- second subplot ---

ax2.plot(x,np.cos(x)         ,linestyle='--',label=r'$\cos \big( x \big)$')
ax2.plot(x,np.cos(x-np.pi/4.),linestyle='--',label=r'$\cos \big( x - \tfrac{\pi}{4} \big)$')

ax2.set_title('Second subplot')

ax2.xaxis.set_ticklabels(['0',r'$\pi$',r'$2\pi$'])
ax2.xaxis.set_ticks([0,np.pi,2*np.pi])
ax2.yaxis.set_ticks([-1,0,1])

ax2.legend(loc='upper center')

ax2.set_xlim([0,2*np.pi])

ax2.set_xlabel(r'$x$')
ax2.set_ylabel(r'$y$')

# --- save/show ---

plt.savefig('subplot.svg')
plt.show()

Legend - background

../../_images/legend_background.svg

[source: legend_background.py]


import numpy             as np
import matplotlib.pyplot as plt

plt.style.use(['goose', 'goose-latex'])

fig, ax = plt.subplots()

for i in range(10):
  ax.plot([0,1], [i/10,(i+10)/10], label=r'$i = {0:d}$'.format(i))

ax.legend(loc='center right', facecolor='white', framealpha=1)

plt.savefig('legend_background.svg')
plt.show()

Legend - external

../../_images/legend_external.svg

[source: legend_external.py]


import numpy             as np
import matplotlib.pyplot as plt

plt.style.use(['goose', 'goose-latex'])

fig, ax = plt.subplots(figsize=(9,6))

x = np.arange(10)

for i in range(5):
  ax.plot(x, i*x, label='$y = {:d}x$'.format(i))

legend = ax.legend(loc='center left', bbox_to_anchor=(1., 0.5), fancybox=True, shadow=True)

frame = legend.get_frame()
frame.set_facecolor('white')
frame.set_edgecolor('black')

plt.savefig('legend_external.svg')
plt.show()

Line-color from colormap

[source: plot-cmap.py]

Note

This example features a colorbar where the ‘ticks’ are placed in the middle of the color blocks. Should you be interested in something simpler, you could also use:

sm   = plt.cm.ScalarMappable(cmap=cmap, norm=mpl.colors.Normalize(vmin=0,vmax=2))
sm.set_array([])

cbar = fig.colorbar(sm)
cbar.set_ticks(...)
cbar.set_ticklabels(...)
import numpy             as np
import matplotlib        as mpl
import matplotlib.pyplot as plt

plt.style.use(['goose','goose-latex'])

x      = np.linspace(0, 5, 100)
N      = 21
cmap   = plt.get_cmap('jet',N)

fig,ax = plt.subplots()

for i,n in enumerate(np.linspace(0,2,N)):
  ax.plot(x, np.sin(x)*x**n, color=cmap(i))

ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')

sm   = plt.cm.ScalarMappable(cmap=cmap, norm=mpl.colors.Normalize(vmin=0,vmax=N))
sm.set_array([])

cbar = plt.colorbar(sm, ticks=np.linspace(0,N-1,(N+1)/2), boundaries=np.linspace(0,N,N+1)-.5)
cbar.ax.set_yticklabels(['{0:.1f}'.format(i) for i in np.linspace(0,2,(N+1)/2)])

plt.savefig('plot-cmap.svg')
plt.show()
../../_images/plot-cmap.svg

Aligning tick labels

[source: tick-position.py]

This example is just a copy of this nice answer. See also the blog of the author.

Note

Also take note of:

ax.set_xticklabels(xlabels, ha='center')
ax.set_yticklabels(ylabels, va='center')
import numpy             as np
import matplotlib.pyplot as plt

n       = 5
x       = np.arange(n)
y       = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]

plt.style.use(['goose', 'goose-latex'])

fig, ax = plt.subplots()

ax.plot(x,y, 'o-')

ax.set_xticks(x)

labels = ax.set_xticklabels(xlabels)

for i, label in enumerate(labels):
  label.set_y(label.get_position()[1] - (i % 2) * 0.075)

plt.savefig('tick-position.svg')
plt.show()

../../_images/tick-position.svg

Tick formatter

[source: tick-formatter.py]

Note

Use matplotlib.ticker.FormatStrFormatter(...) to use the old-style sprintf format.

import numpy             as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.style.use(['goose', 'goose-latex'])

x = np.linspace(0,10,101)
y = x**2.

fig, ax = plt.subplots()

ax.plot(x, y)

ax.yaxis.set_major_formatter(ticker.StrMethodFormatter(r'${x:.1e}$'))

plt.savefig('tick-formatter.svg')
plt.show()

../../_images/tick-formatter.svg

Image

[source: image.py]


import numpy             as np
import matplotlib.pyplot as plt

plt.style.use(['goose','goose-latex'])

x,y  = np.meshgrid(np.linspace(0,1,100),np.linspace(0,1,100))
d    = np.sqrt(x**2+y**2)

fig,ax = plt.subplots()

cax  = ax.imshow(d)

cbar = fig.colorbar(cax,aspect=10)
cbar.set_ticks([0,np.sqrt(2.)])
cbar.set_ticklabels(['0',r'$\sqrt{2}$'])

ax.xaxis.set_ticks(range(0,101,20))
ax.yaxis.set_ticks(range(0,101,20))

ax.set_xlim([0,100])
ax.set_ylim([0,100])

ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')

plt.savefig('image.svg')
plt.show()
../../_images/image.svg

Colorbar

Basic

[source: image_subplots.py]


import numpy             as np
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.style.use(['goose','goose-latex'])

# --- some data ----

a,b = np.meshgrid(np.linspace(0,1,100),np.linspace(0,1,100))
d   = np.sqrt(a**2+b**2)

# --- open figure with three axes ---

fig, axes  = plt.subplots(ncols=3, figsize=(18,6))

# --- left subplot ---

ax   = axes[0]
im   = ax.imshow(a,clim=(0,1))
ax.xaxis.set_ticks([0,100])
ax.yaxis.set_ticks([0,100])
ax.set_xlim([0,100])
ax.set_ylim([0,100])
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.set_title(r'$a$')
div  = make_axes_locatable(ax)
cax  = div.append_axes('right', size='5%', pad=0.1)
cbar = plt.colorbar(im,cax=cax)
cbar.set_ticks([0,1])

# --- middle subplot ---

ax   = axes[1]
im   = ax.imshow(b,clim=(0,1))
ax.xaxis.set_ticks([0,100])
ax.yaxis.set_ticks([0,100])
ax.set_xlim([0,100])
ax.set_ylim([0,100])
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.set_title(r'$b$')
div  = make_axes_locatable(ax)
cax  = div.append_axes('right', size='5%', pad=0.1)
cbar = plt.colorbar(im,cax=cax)
cbar.set_ticks([0,1])

# --- right subplot ---

ax   = axes[2]
im   = ax.imshow(d,clim=(0,1))
ax.xaxis.set_ticks([0,100])
ax.yaxis.set_ticks([0,100])
ax.set_xlim([0,100])
ax.set_ylim([0,100])
ax.set_xlabel(r'$x$')
ax.set_ylabel(r'$y$')
ax.set_title(r'$\sqrt{a^2 + b^2}$')
div  = make_axes_locatable(ax)
cax  = div.append_axes('right', size='5%', pad=0.1)
cbar = plt.colorbar(im,cax=cax)
cbar.set_ticks([0,1])

# --- save/show ---

plt.savefig('image_subplots.svg')
plt.show()
../../_images/image_subplots.svg

Colorbar positioning

[source: image_subplots_bottom.py]


import numpy             as np
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.style.use(['goose','goose-latex'])

# --- some data ----

a,b = np.meshgrid(np.linspace(0,1,100),np.linspace(0,1,100))
d   = np.sqrt(a**2+b**2)

# --- open figure with three axes ---

fig, axes  = plt.subplots(ncols=3, figsize=(18,6))

# --- left subplot ---

ax   = axes[0]
im   = ax.imshow(a,clim=(0,1))
ax.xaxis.set_ticks([0,100])
ax.yaxis.set_ticks([0,100])
ax.set_xlim([0,100])
ax.set_ylim([0,100])
ax.set_title(r'$a$')
div  = make_axes_locatable(ax)
cax  = div.append_axes('bottom', size='5%', pad=0.4)
cbar = plt.colorbar(im,cax=cax, orientation='horizontal')
cbar.set_ticks([0,1])

# --- middle subplot ---

ax   = axes[1]
im   = ax.imshow(b,clim=(0,1))
ax.xaxis.set_ticks([0,100])
ax.yaxis.set_ticks([0,100])
ax.set_xlim([0,100])
ax.set_ylim([0,100])
ax.set_title(r'$b$')
div  = make_axes_locatable(ax)
cax  = div.append_axes('bottom', size='5%', pad=0.4)
cbar = plt.colorbar(im,cax=cax, orientation='horizontal')
cbar.set_ticks([0,1])

# --- right subplot ---

ax   = axes[2]
im   = ax.imshow(d,clim=(0,1))
ax.xaxis.set_ticks([0,100])
ax.yaxis.set_ticks([0,100])
ax.set_xlim([0,100])
ax.set_ylim([0,100])
ax.set_title(r'$\sqrt{a^2 + b^2}$')
div  = make_axes_locatable(ax)
cax  = div.append_axes('bottom', size='5%', pad=0.4)
cbar = plt.colorbar(im,cax=cax, orientation='horizontal')
cbar.set_ticks([0,1])

# --- save/show ---

plt.savefig('image_subplots_bottom.svg')
plt.show()
../../_images/image_subplots_bottom.svg

Stand-alone colorbar

[source: colorbar.py]


import matplotlib.pyplot as plt
import matplotlib        as mpl

plt.style.use(['goose','goose-latex'])

fig,ax = plt.subplots(figsize=(8, 2))

cbar = mpl.colorbar.ColorbarBase(ax,
  cmap        = mpl.cm.get_cmap('RdBu_r'),
  norm        = mpl.colors.Normalize(vmin=5, vmax=10),
  orientation = 'horizontal'
)

cbar.set_label('Some Units')

plt.savefig('colorbar.svg')
plt.show()
../../_images/colorbar.svg

Colormap

Combined colormap

[source: colormap.py]

This example shows how to create a custom colormap. To do this one has to create an RGBA-matrix: a matrix with on each row the amount (between 0 and 1) of Red, Green, Blue, and Alpha (transparency; 0 means that the pixel does not have any coverage information and is transparent).

As an example the distance to some point is plotted in two dimensions. Then:

  • For any distance higher than some critical value, the colors will be taken from a standard colormap.
  • For any distance lower than some critical value, the colors will linearly go from white to the first color of the previously mentioned map.

Note

The choices depend fully on what you want to show. The colormaps and their sizes depend on your problem. For example, you can choose different types of interpolation: linear, exponential, …; single- or multi-color colormaps; etc..

Note

The choices depend fully on what you want to show. The colormaps and their sizes depend on your problem. For example you can choose a different types of interpolation: linear, exponential, …; single- or multi-color colormaps; etc..


import numpy             as np
import matplotlib        as mpl
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.style.use(['goose','goose-latex'])

# create colormap
# ---------------

# create a colormap that consists of
# - 1/5 : custom colormap, ranging from white to the first color of the colormap
# - 4/5 : existing colormap

# set upper part: 4 * 256/4 entries
upper = mpl.cm.jet(np.arange(256))

# set lower part: 1 * 256/4 entries
# - initialize all entries to 1 to make sure that the alpha channel (4th column) is 1
lower = np.ones((int(256/4),4))
# - modify the first three columns (RGB):
#   range linearly between white (1,1,1) and the first color of the upper colormap
for i in range(3):
  lower[:,i] = np.linspace(1, upper[0,i], lower.shape[0])

# combine parts of colormap
cmap = np.vstack(( lower, upper ))

# convert to matplotlib colormap
cmap = mpl.colors.ListedColormap(cmap, name='myColorMap', N=cmap.shape[0])

# show some example
# -----------------

# open a new figure
fig, ax = plt.subplots()

# some data to plot: distance to point at (50,50)
x,y = np.meshgrid(np.linspace(0,99,100),np.linspace(0,99,100))
z   = (x-50)**2. + (y-50)**2.

# plot data, apply colormap, set limit such that our interpretation is correct
im = ax.imshow(z, cmap=cmap, clim=(0,5000))

# add a colorbar to the bottom of the image
div  = make_axes_locatable(ax)
cax  = div.append_axes('bottom', size='5%', pad=0.4)
cbar = plt.colorbar(im, cax=cax, orientation='horizontal')

# save/show the image
plt.savefig('colormap.svg')
plt.show()
../../_images/colormap.svg

Sub-colormap vs. interpolated colormap

[source: colormap-part.py]

This example contains a simple example to derive a custom colormap from an existing colormap, see this answer.


import numpy             as np
import matplotlib.pyplot as plt
import matplotlib        as mpl

from mpl_toolkits.axes_grid1 import make_axes_locatable

plt.style.use(['goose','goose-latex'])

np.random.seed(1)
data = np.sort(np.random.rand(8,12))

fig, axes = plt.subplots(figsize=(16,8), ncols=2)

cmap = mpl.cm.jet(np.linspace(0,1,20))
cmap = mpl.colors.ListedColormap(cmap[10:,:-1])

ax   = axes[0]
c    = ax.pcolor(data, edgecolors='k', linewidths=4, cmap=cmap, vmin=0.0, vmax=1.0)
div  = make_axes_locatable(ax)
cax  = div.append_axes('right', size='5%', pad=0.1)
cbar = plt.colorbar(c,cax=cax)

cmap = mpl.cm.jet(np.linspace(0,1,20))
cmap = mpl.colors.LinearSegmentedColormap.from_list('test', [cmap[10,:-1], cmap[-1,:-1]], N=10)

ax   = axes[1]
c    = ax.pcolor(data, edgecolors='k', linewidths=4, cmap=cmap, vmin=0.0, vmax=1.0)
div  = make_axes_locatable(ax)
cax  = div.append_axes('right', size='5%', pad=0.1)
cbar = plt.colorbar(c,cax=cax)

plt.savefig('colormap-part.svg')
plt.show()

../../_images/colormap-part.svg