Examples#

Plot#

Basic#

../../_images/plot.svg

source: plot.py

import matplotlib.pyplot as plt
import numpy as np

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(x)$")
ax.plot(x, np.sin(x - np.pi / 4.0), label=r"$\sin(x - \pi/4)$")

ax.set_title("Simple plot")

ax.xaxis.set_ticks([0, np.pi, 2 * np.pi])
ax.xaxis.set_ticklabels(["0", r"$\pi$", r"$2\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.close()

Subplot#

../../_images/subplot.svg

source: subplot.py

import matplotlib.pyplot as plt
import numpy as np

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(x)$")
ax1.plot(x, np.sin(x - np.pi / 4.0), label=r"$\sin(x - \pi/4)$")

ax1.set_title("First subplot")

ax1.xaxis.set_ticks([0, np.pi, 2 * np.pi])
ax1.xaxis.set_ticklabels(["0", r"$\pi$", r"$2\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(x)$")
ax2.plot(x, np.cos(x - np.pi / 4.0), linestyle="--", label=r"$\cos(x - \pi/4)$")

ax2.set_title("Second subplot")

ax2.xaxis.set_ticks([0, np.pi, 2 * np.pi])
ax2.xaxis.set_ticklabels(["0", r"$\pi$", r"$2\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.close()

Legend#

Set background colour#

../../_images/legend_background.svg

source: legend_background.py

import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()

for i in range(10):
    x = [0, 1]
    y = [i / 10, (i + 10) / 10]
    ax.plot(x, y, label=rf"$i = {i:d}$")

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

plt.savefig("legend_background.svg")
plt.close()

Move legend outside the plot#

../../_images/legend_external.svg

source: legend_external.py

import matplotlib.pyplot as plt
import numpy as np

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=f"$y = {i:d}x$")

legend = ax.legend(loc="center left", bbox_to_anchor=(1.0, 0.5), fancybox=True, shadow=True)

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

plt.savefig("legend_external.svg")
plt.close()

Line-color from colormap#

With colorbar#

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 matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

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)):
    y = np.sin(x) * x**n
    ax.plot(x, y, 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([])

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

plt.savefig("plot-cmap.svg")
plt.close()
../../_images/plot-cmap.svg

Using cycler#

source: plot-cycler.py

Note

The cycler can also be used to cycle through line-styles. E.g.

custom_cycler = (cycler(color=['r', 'g', 'b', 'y']) +
                 cycler(linestyle=['-', '--', ':', '-.']))
import matplotlib.pyplot as plt
import numpy as np
from cycler import cycler

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

x = np.linspace(0, 5, 100)
N = 21
cmap = plt.get_cmap("jet", N)
custom_cycler = cycler(color=[cmap(i) for i in range(N)])
plt.rc("axes", prop_cycle=custom_cycler)

fig, ax = plt.subplots()

for n in np.linspace(0, 2, N):
    y = np.sin(x) * x**n
    ax.plot(x, y)

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

plt.savefig("plot-cycler.svg")
plt.close()
../../_images/plot-cycler.svg

Multi-colour line#

source: multicolor.py

Note

References

StackOverflow

import matplotlib.pyplot as plt
import numpy as np

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

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

fig, ax = plt.subplots()

ax.plot(x, y, linestyle=(0, (10, 20)), color="r")
ax.plot(x, y, linestyle=(10, (10, 20)), color="g")
ax.plot(x, y, linestyle=(20, (10, 20)), color="b")

plt.savefig("multicolor.svg")
../../_images/multicolor.svg

Ticks#

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 matplotlib.pyplot as plt
import numpy as np

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

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

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.close()
../../_images/tick-position.svg

Tick formatter#

source: tick-formatter.py

Note

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

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

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

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

fig, ax = plt.subplots()

ax.plot(x, y)

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

plt.savefig("tick-formatter.svg")
plt.close()
../../_images/tick-formatter.svg

Logarithmic scale#

Tick rotation#

source: tick-rotation-log.py

import matplotlib
import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()

ax.set_xscale("log")
ax.set_yscale("log")

ax.set_xlim([2e-2, 2e-1])
ax.set_ylim([2e1, 2e3])

ax.plot([0.01, 0.1, 1.0], [20, 200, 2000])

ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.ScalarFormatter())

plt.setp(ax.xaxis.get_majorticklabels(), rotation=45)
plt.setp(ax.xaxis.get_minorticklabels(), rotation=45)

plt.savefig("tick-rotation-log.svg")
plt.close()
../../_images/tick-rotation-log.svg
Specifying ticks#

source: tick-log_1.py

import matplotlib
import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()

ax.set_xscale("log")
ax.set_yscale("log")

ax.set_xlim([2e-2, 2e-1])
ax.set_ylim([2e1, 2e3])

ax.plot([0.02, 0.1, 0.2], [20, 1000, 2000])

ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.ScalarFormatter())

ax.set_xticks([])
ax.set_xticks([], minor=True)
ax.set_xticks([0.02, 0.1, 0.2])

plt.savefig("tick-log_1.svg")
plt.close()
../../_images/tick-log_1.svg
Selecting ticks#

source: tick-log_2.py

To have ticks at multiples of 1 and 2 of integer powers of the logarithmic base (10) use matplotlib.ticker.LogLocator(subs=(1,2,)). Then use matplotlib.ticker.NullLocator() to turn minor labels off.

import matplotlib
import matplotlib.pyplot as plt

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

fig, ax = plt.subplots()

ax.set_xscale("log")
ax.set_yscale("log")

ax.set_xlim([2e-2, 2e-1])
ax.set_ylim([2e1, 2e3])

ax.plot([0.02, 0.1, 0.2], [20, 1000, 2000])

ax.xaxis.set_major_locator(
    matplotlib.ticker.LogLocator(
        subs=(
            1,
            2,
        )
    )
)
ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

plt.savefig("tick-log_2.svg")
plt.close()
../../_images/tick-log_2.svg

Image#

source: image.py

import matplotlib.pyplot as plt
import numpy as np

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.0)])
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.close()
../../_images/image.svg

Colorbar#

Basic#

source: image_subplots.py

import matplotlib.pyplot as plt
import numpy as np
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.close()
../../_images/image_subplots.svg

Orientation#

source: image_subplots_bottom.py

import matplotlib.pyplot as plt
import numpy as np
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.close()
../../_images/image_subplots_bottom.svg

Grid#

source: image_subplots_grid.py

import matplotlib.pyplot as plt
import numpy as np

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

fig, axes = plt.subplots(figsize=(8, 8), ncols=2, nrows=2, constrained_layout=True)

for ax in axes.ravel():
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

data = np.random.random([10, 10])
mappable = np.empty(axes.shape, dtype=object)

for row in range(axes.shape[0]):
    for col in range(axes.shape[1]):
        mappable[row, col] = axes[row, col].imshow(data, cmap="jet", clim=(0, 1))

cbar = fig.colorbar(mappable[-1, 0], ax=axes[-1, :], orientation="horizontal")
cbar.set_label(r"$v$")

axes[0, 0].set_title(r"first")
axes[0, 1].set_title(r"second")

fig.savefig("image_subplots_grid.svg")
plt.close(fig)
../../_images/image_subplots_grid.svg

Stand-alone colorbar#

source: colorbar.py

import matplotlib as mpl
import matplotlib.pyplot as plt

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.close()
../../_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 n your problem. For example you can choose a different types of interpolation: linear, exponential, …; single- or multi-color colormaps; etc..

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
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.0 + (y - 50) ** 2.0

# 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.close()
../../_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 matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
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.close()
../../_images/colormap-part.svg