Matplotlib snippets

Jérémie Decock (www.jdhp.org)

Last update: 2017-07-20

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

# Build datas ###############

x = np.arange(-10, 10, 0.01)
y = np.sin(x)

# Plot data #################

fig = plt.figure(figsize=(8.0, 8.0))
ax = fig.add_subplot(111)

ax.plot(x, y)

# Set labels ################

ax.set_xlabel(r"$x$", fontsize=32)
ax.set_ylabel(r"$f(x)$", fontsize=32)

# Save file and plot ########

#plt.savefig("ax_set_label.png")
plt.show()
In [3]:
import numpy as np
import matplotlib.pyplot as plt

# Build datas ###############

x = np.arange(-10, 10, 0.01)
y = np.sin(x)

# Plot data #################

fig = plt.figure(figsize=(8.0, 8.0))
ax = fig.add_subplot(111)

ax.plot(x, y, label="Test")

# Set legend ################

ax.legend(loc='lower right', fontsize=20)

# Save file and plot ########

#plt.savefig("ax_set_legend.png")
plt.show()
In [4]:
import numpy as np
import matplotlib.pyplot as plt

# Build datas ###############

x = np.arange(-10., 10., 0.1)
y = np.power(x, 2)

# Plot data #################

fig, ax = plt.subplots(1, 1)

ax.plot(x, y)

ax.set_title(r"$x^2$")

# Save file and plot ########

#plt.savefig("ax_set_title.png")
plt.show()
In [5]:
import numpy as np
import matplotlib.pyplot as plt

# Build datas ###############

x = np.arange(-10., 10., 0.1)
y = np.cos(x)

# Plot data #################

fig, ax = plt.subplots(1, 1)

ax.plot(x, y)

ax.set_xlim([-np.pi, np.pi])
ax.set_ylim([-1, 1])

# Save file and plot ########

#plt.savefig("ax_set_xylim.png")
plt.show()
In [6]:
import numpy as np
import matplotlib.pyplot as plt

import matplotlib.patches as patches

# Plot data #################

#fig, ax = plt.subplots(figsize=(5, 5))
fig, (ax1, ax2) = plt.subplots(ncols=2)

ax1.plot([0, 1])
ax2.plot([0, 1])

ax2.axis('equal')              # <- SAME SCALE ON X AND Y

# Save file #################

#plt.savefig("axis_equal.png")

# Plot ######################

plt.show()
In [7]:
import numpy as np
import matplotlib.pyplot as plt

WIDTH = 0.4       # the width of the bars

# Build datas ###############

x = np.arange(-5, 6)
y1 = np.power(x, 2)
y2 = np.power(x, 3)

# Plot data #################

fig = plt.figure()
ax = fig.add_subplot(111)

ax.bar(x, y1, WIDTH, color='r')
ax.bar(x + WIDTH, y2, WIDTH, color='b')

# Save file and plot ########

#plt.savefig("bar.png")
plt.show()
In [8]:
import matplotlib.pyplot as plt

# Get a list of the colormaps in matplotlib. 
maps = sorted(plt.cm.datad)

print(maps)
['Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap', 'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd', 'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r', 'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Vega10', 'Vega10_r', 'Vega20', 'Vega20_r', 'Vega20b', 'Vega20b_r', 'Vega20c', 'Vega20c_r', 'Wistia', 'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot', 'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'cubehelix', 'cubehelix_r', 'flag', 'flag_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r', 'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r', 'hot', 'hot_r', 'hsv', 'hsv_r', 'jet', 'jet_r', 'nipy_spectral', 'nipy_spectral_r', 'ocean', 'ocean_r', 'pink', 'pink_r', 'prism', 'prism_r', 'rainbow', 'rainbow_r', 'seismic', 'seismic_r', 'spectral', 'spectral_r', 'spring', 'spring_r', 'summer', 'summer_r', 'tab10', 'tab10_r', 'tab20', 'tab20_r', 'tab20b', 'tab20b_r', 'tab20c', 'tab20c_r', 'terrain', 'terrain_r', 'winter', 'winter_r']
In [9]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import NonUniformImage
from matplotlib import cm

X_MIN=0
X_MAX=100
X_STEP=5

Y_MIN=0
Y_MAX=100
Y_STEP=5

# Build datas ###############

x = np.arange(X_MIN, X_MAX, X_STEP)
y = np.arange(Y_MIN, Y_MAX, Y_STEP)
z_matrix = np.array([[xi * yi for xi in range(X_MIN, X_MAX, X_STEP)] for yi in range(Y_MIN, Y_MAX, Y_STEP)])

# Plot data #################

fig = plt.figure()
ax = fig.add_subplot(111)

#interp='nearest'     # "raw" (non smooth) map
interp = 'bilinear'   # "smooth" map

# NonUniformImage permet de définir la position des éléments de 'z_matrix' sur
# les axes.
# Sans NonUniformImage, une matrice 'z_matrix' de taille (sx, sy) serait
# dessinée sur un repère avec un axe des abscisses allant de 0 a sx et un axe
# des ordonnées allant de 0 a sy.
im = NonUniformImage(ax, interpolation=interp, extent=(X_MIN, X_MAX, Y_MIN, Y_MAX), cmap=cm.binary)

# im.set_data(x, y, A)
#   Set the grid for the pixel centers, and the pixel values.
#   *x* and *y* are 1-D ndarrays of lengths N and M, respectively, specifying pixel centers
#   *A* is an (M,N) ndarray or masked array of values to be colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA array.
im.set_data(x, y, z_matrix)

ax.images.append(im)

ax.set_xlim(X_MIN, X_MAX)
ax.set_ylim(Y_MIN, Y_MAX)

fig.colorbar(im) # draw colorbar

# Save file and plot ########

#plt.savefig("colour_map_with_custom_axes.png")
plt.show()
In [10]:
import numpy as np
import matplotlib.pyplot as plt

# Build datas ###############

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)

Z = X * np.exp(-X**2 - Y**2)

# Plot data #################

fig, ax = plt.subplots()

max_value = np.max(Z)
levels = np.array([0.1*max_value, 0.3*max_value, 0.6*max_value])

cs = plt.contour(x, y, Z, levels,
                 linewidths=(2, 2, 3), linestyles=('dotted', 'dashed', 'solid'),
                 alpha=0.5, colors='blue', label="TC")
ax.clabel(cs, inline=False, fontsize=12)

# Set title and labels ######

ax.set_title("Contour", fontsize=20)
ax.set_xlabel(r"$X_1$", fontsize=20)
ax.set_ylabel(r"$X_2$", fontsize=20)

# Set legend ################

lines = [ cs.collections[0]]
labels = ['X']
ax.legend(lines, labels, prop={'size': 14}, loc='best', fancybox=True, framealpha=0.5)

# Save file #################

#plt.savefig("contour.png")

# Plot ######################

plt.show()
In [11]:
import numpy as np
import matplotlib.pyplot as plt

# Build datas ###############

x1, y1 = np.random.exponential(size=(2, 100000))
x2, y2 = np.random.exponential(size=(2, 100000)) * 10.

xbins = np.logspace(-2, 3, 30)
ybins = np.logspace(-2, 3, 30)

counts1, xedges, yedges = np.histogram2d(x1, y1, bins=(xbins, ybins))
counts2, xedges, yedges = np.histogram2d(x2, y2, bins=(xbins, ybins))

# Plot data #################

fig, ax = plt.subplots()

max_value = max(np.max(counts1), np.max(counts2))

levels = np.array([0.1*max_value, 0.3*max_value, 0.6*max_value])

cs1 = plt.contour(xedges[:-1], yedges[:-1], counts1.T, levels,
                  linewidths=(2, 2, 3), linestyles=('dotted', 'dashed', 'solid'),
                  alpha=0.5, colors='blue', label="TC")
ax.clabel(cs1, inline=False, fontsize=12)

cs2 = plt.contour(xedges[:-1], yedges[:-1], counts2.T, levels,
                  linewidths=(2, 2, 3), linestyles=('dotted', 'dashed', 'solid'),
                  alpha=0.5, colors='red', label="WT")
ax.clabel(cs2, inline=False, fontsize=12)

#ax.set_xlim(1e1, 1e4)
#ax.set_ylim(1e1, 1e4)

ax.set_yscale('log')
ax.set_xscale('log')

# Set title and labels ######

ax.set_title("Contour", fontsize=20)
ax.set_xlabel(r"$X_1$", fontsize=20)
ax.set_ylabel(r"$X_2$", fontsize=20)

# Set legend ################

lines = [ cs1.collections[0], cs2.collections[0]]
labels = ['E1','E2']
ax.legend(lines, labels, prop={'size': 14}, loc='best', fancybox=True, framealpha=0.5)

# Save file #################

#plt.savefig("contour_from_hist2d.png")

# Plot ######################

plt.show()

Plot contours from an 2D histogram showing the standard deviation

Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/contour_from_hist2d_sigmas.py

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

# Build datas ###############

x, y = np.random.normal(size=(2, 1000000))

xbins = np.linspace(-2, 2, 30)
ybins = np.linspace(-2, 2, 30)

counts, xedges, yedges = np.histogram2d(x, y, bins=(xbins, ybins))

print("std(x)=", np.std(x))
print("std(y)=", np.std(y))

# Plot data #################

fig, ax = plt.subplots()

sigmas = [1., 2., 3.]
levels = []
fmt = {}

for sigma in sigmas:
    levels.append(float(sigma) * np.std(counts))
    fmt[float(sigma) * np.std(counts)] = r"${}\sigma$".format(int(sigma))

cs = plt.contour(xedges[:-1], yedges[:-1], counts.T, levels,
                  linewidths=(2, 2, 3), linestyles=('dotted', 'dashed', 'solid'),
                  alpha=0.8, colors='red')
ax.clabel(cs, inline=True, fontsize=16, fmt=fmt)

# Set title and labels ######

ax.set_title("Contour", fontsize=20)
ax.set_xlabel(r"$X_1$", fontsize=20)
ax.set_ylabel(r"$X_2$", fontsize=20)

# Set legend ################

lines = [ cs.collections[0]]
labels = [r'$\mathcal{N}$']
ax.legend(lines, labels, prop={'size': 14}, loc='best', fancybox=True, framealpha=0.5)

# Save file #################

#plt.savefig("contour_from_hist2d_sigmas.png")

# Plot ######################

plt.show()
std(x)= 0.999306295601
std(y)= 1.00056385993
In [13]:
import numpy as np
import matplotlib.pyplot as plt
import math

import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.path as mpath
import itertools

TITLE_FONT_SIZE = 9

fig, axis_array = plt.subplots(nrows=4,
                               ncols=5,
                               squeeze=False,   # <- Always make a 2D array, whatever nrows and ncols
                               figsize=(12.5, 6))

axs = axis_array.flat

for ax in axs:
    ax.axis('equal')      # same scale on X and Y
    ax.set_xlim(-5, 5)
    ax.set_ylim(-5, 5)
    ax.set_axis_off()

fill_color = "red"
line_color = "blue"
line_width = 2.
line_style = 'dashed'     # 'solid' (default), 'dashed', 'dashdot', 'dotted'   see: http://matplotlib.org/examples/lines_bars_and_markers/linestyles.html
join_style = "miter"      # 'miter', 'round', 'bevel'                          see: http://matplotlib.org/examples/api/joinstyle.html
fill = True               # True or False
fill_pattern = "/"        # "/", "\\", '-', '+', 'x', 'o', 'O', '.', '*'
alpha = 0.5

it = itertools.count()

# DRAW A LINE #################################################################

ax = axs[next(it)]

p1_x = -4
p1_y = -3

p2_x = 0
p2_y = 3

p3_x = 4
p3_y = -3

line = mlines.Line2D((p1_x, p2_x, p3_x),
                     (p1_y, p2_y, p3_y),
                     # COMMON OPTIONS:
                     alpha=alpha,
                     lw=line_width,
                     linestyle=line_style,
                     color=line_color)
ax.add_line(line)
ax.set_title("matplotlib.patches.Line2D", fontsize=TITLE_FONT_SIZE)

# DRAW AN ARROW ###############################################################

ax = axs[next(it)]

pt_start_x = -4.
pt_start_y = -3.

length_x = 8.
length_y = 6.

width = 3.

patch = mpatches.Arrow(x=pt_start_x,
                       y=pt_start_y,
                       dx=length_x,
                       dy=length_y,
                       width=width,
                       # COMMON OPTIONS:
                       alpha=alpha,
                       fill=fill,
                       facecolor=fill_color,
                       hatch=fill_pattern,
                       ec=line_color,
                       lw=line_width,
                       joinstyle=join_style,
                       linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.Arrow", fontsize=TITLE_FONT_SIZE)

# DRAW A RECTANGLE ############################################################

ax = axs[next(it)]

lower_left_point = (-4., -3.)
width = 8
height = 6
angle = 0.

patch = mpatches.Rectangle(lower_left_point,
                           width=width,
                           height=height,
                           angle=angle, 
                           # COMMON OPTIONS:
                           alpha=alpha,
                           fill=fill,
                           facecolor=fill_color,
                           hatch=fill_pattern,
                           ec=line_color,
                           lw=line_width,
                           joinstyle=join_style,
                           linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.Rectangle", fontsize=TITLE_FONT_SIZE)

# DRAW A FANCY BBOX PATCH #####################################################

ax = axs[next(it)]

lower_left_point = (-4., -3.)
width = 8
height = 6
box_style = 'darrow'       # 'circle', 'darrow', 'larrow', 'rarrow', 'round', 'round4', 'roundtooth', 'sawtooth', 'square'
bbox_transmuter = None
mutation_scale = 1.0       # a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1.
mutation_aspect = None     # The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None.

patch = mpatches.FancyBboxPatch(xy=lower_left_point,
                                width=width,
                                height=height,
                                boxstyle=box_style,
                                bbox_transmuter=bbox_transmuter,
                                mutation_scale=mutation_scale,
                                mutation_aspect=mutation_aspect,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.FancyBboxPatch\nDArrow", fontsize=TITLE_FONT_SIZE)

# DRAW A FANCY BBOX PATCH #####################################################

ax = axs[next(it)]

lower_left_point = (-4., -3.)
width = 8
height = 6
box_style = 'larrow'       # 'circle', 'darrow', 'larrow', 'rarrow', 'round', 'round4', 'roundtooth', 'sawtooth', 'square'
bbox_transmuter = None
mutation_scale = 1.0       # a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1.
mutation_aspect = None     # The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None.

patch = mpatches.FancyBboxPatch(xy=lower_left_point,
                                width=width,
                                height=height,
                                boxstyle=box_style,
                                bbox_transmuter=bbox_transmuter,
                                mutation_scale=mutation_scale,
                                mutation_aspect=mutation_aspect,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.FancyBboxPatch\nLArrow", fontsize=TITLE_FONT_SIZE)

# DRAW A FANCY BBOX PATCH #####################################################

ax = axs[next(it)]

lower_left_point = (-4., -3.)
width = 8
height = 6
box_style = 'rarrow'       # 'circle', 'darrow', 'larrow', 'rarrow', 'round', 'round4', 'roundtooth', 'sawtooth', 'square'
bbox_transmuter = None
mutation_scale = 1.0       # a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1.
mutation_aspect = None     # The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None.

patch = mpatches.FancyBboxPatch(xy=lower_left_point,
                                width=width,
                                height=height,
                                boxstyle=box_style,
                                bbox_transmuter=bbox_transmuter,
                                mutation_scale=mutation_scale,
                                mutation_aspect=mutation_aspect,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.FancyBboxPatch\nRArrow", fontsize=TITLE_FONT_SIZE)

# DRAW A FANCY BBOX PATCH #####################################################

ax = axs[next(it)]

lower_left_point = (-4., -3.)
width = 8
height = 6
box_style = mpatches.BoxStyle.Round(pad=0.3, rounding_size=2.)
bbox_transmuter = None
mutation_scale = 1.0       # a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1.
mutation_aspect = None     # The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None.

patch = mpatches.FancyBboxPatch(xy=lower_left_point,
                                width=width,
                                height=height,
                                boxstyle=box_style,
                                bbox_transmuter=bbox_transmuter,
                                mutation_scale=mutation_scale,
                                mutation_aspect=mutation_aspect,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.FancyBboxPatch\nRound", fontsize=TITLE_FONT_SIZE)

# DRAW A FANCY BBOX PATCH #####################################################

ax = axs[next(it)]

lower_left_point = (-4., -3.)
width = 8
height = 6
box_style = mpatches.BoxStyle.Round4(pad=0.3, rounding_size=1.)
bbox_transmuter = None
mutation_scale = 1.0       # a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1.
mutation_aspect = None     # The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None.

patch = mpatches.FancyBboxPatch(xy=lower_left_point,
                                width=width,
                                height=height,
                                boxstyle=box_style,
                                bbox_transmuter=bbox_transmuter,
                                mutation_scale=mutation_scale,
                                mutation_aspect=mutation_aspect,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.FancyBboxPatch\nRound4", fontsize=TITLE_FONT_SIZE)

# DRAW A FANCY BBOX PATCH #####################################################

ax = axs[next(it)]

lower_left_point = (-4., -3.)
width = 8
height = 6
box_style = mpatches.BoxStyle.Roundtooth(pad=0.3, tooth_size=0.5)
bbox_transmuter = None
mutation_scale = 1.0       # a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1.
mutation_aspect = None     # The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None.

patch = mpatches.FancyBboxPatch(xy=lower_left_point,
                                width=width,
                                height=height,
                                boxstyle=box_style,
                                bbox_transmuter=bbox_transmuter,
                                mutation_scale=mutation_scale,
                                mutation_aspect=mutation_aspect,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle='solid')

ax.add_patch(patch)
ax.set_title("matplotlib.patches.FancyBboxPatch\nRoundtooth", fontsize=TITLE_FONT_SIZE)

# DRAW A FANCY BBOX PATCH #####################################################

ax = axs[next(it)]

lower_left_point = (-4., -3.)
width = 8
height = 6
box_style = mpatches.BoxStyle.Sawtooth(pad=0.3, tooth_size=0.5)
bbox_transmuter = None
mutation_scale = 1.0       # a value with which attributes of boxstyle (e.g., pad) will be scaled. default=1.
mutation_aspect = None     # The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it. default=None.

patch = mpatches.FancyBboxPatch(xy=lower_left_point,
                                width=width,
                                height=height,
                                boxstyle=box_style,
                                bbox_transmuter=bbox_transmuter,
                                mutation_scale=mutation_scale,
                                mutation_aspect=mutation_aspect,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle='solid')

ax.add_patch(patch)
ax.set_title("matplotlib.patches.FancyBboxPatch\nSawtooth", fontsize=TITLE_FONT_SIZE)

# DRAW A POLYGON ##############################################################

ax = axs[next(it)]

points = np.array([[-1., 0.],    # a numpy array with shape Nx2
                   [-3., 0.],
                   [-3., -2.]])
closed = False

patch = mpatches.Polygon(xy=points,
                         closed=closed,
                         # COMMON OPTIONS:
                         alpha=alpha,
                         fill=fill,
                         facecolor=fill_color,
                         hatch=fill_pattern,
                         ec=line_color,
                         lw=line_width,
                         joinstyle=join_style,
                         linestyle='solid')

ax.add_patch(patch)

###

points = np.array([[1., 0.],    # a numpy array with shape Nx2
                   [3., 0.],
                   [3., 2.]])
closed = True

patch = mpatches.Polygon(xy=points,
                         closed=closed,
                         # COMMON OPTIONS:
                         alpha=alpha,
                         fill=fill,
                         facecolor=fill_color,
                         hatch=fill_pattern,
                         ec=line_color,
                         lw=line_width,
                         joinstyle=join_style,
                         linestyle='solid')

ax.add_patch(patch)

ax.set_title("matplotlib.patches.Polygon", fontsize=TITLE_FONT_SIZE)

# DRAW A REGULAR POLYGON ######################################################

ax = axs[next(it)]

center = (-2.5, 2.5)
num_vertices = 3
radius = 2.               # the distance from the center to each of the vertices
orientation_rad = 0.      # rotates the polygon (in radians)

patch = mpatches.RegularPolygon(xy=center,
                                numVertices=num_vertices,
                                radius=radius,
                                orientation=orientation_rad,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle='solid')

ax.add_patch(patch)

###

center = (2.5, 2.5)
num_vertices = 4
radius = 2.                       # the distance from the center to each of the vertices
orientation_rad = math.pi/2.      # rotates the polygon (in radians)

patch = mpatches.RegularPolygon(xy=center,
                                numVertices=num_vertices,
                                radius=radius,
                                orientation=orientation_rad,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle='solid')

ax.add_patch(patch)

###

center = (2.5, -2.5)
num_vertices = 5
radius = 2.               # the distance from the center to each of the vertices
orientation_rad = 0.      # rotates the polygon (in radians)

patch = mpatches.RegularPolygon(xy=center,
                                numVertices=num_vertices,
                                radius=radius,
                                orientation=orientation_rad,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle='solid')

ax.add_patch(patch)

###

center = (-2.5, -2.5)
num_vertices = 6
radius = 2.               # the distance from the center to each of the vertices
orientation_rad = 0.      # rotates the polygon (in radians)

patch = mpatches.RegularPolygon(xy=center,
                                numVertices=num_vertices,
                                radius=radius,
                                orientation=orientation_rad,
                                # COMMON OPTIONS:
                                alpha=alpha,
                                fill=fill,
                                facecolor=fill_color,
                                hatch=fill_pattern,
                                ec=line_color,
                                lw=line_width,
                                joinstyle=join_style,
                                linestyle='solid')

ax.add_patch(patch)

ax.set_title("matplotlib.patches.RegularPolygon", fontsize=TITLE_FONT_SIZE)

# DRAW A CIRCLE ###############################################################

ax = axs[next(it)]

center = (0., 0.)         # center of the circle
radius = 4.               # radius of the circle

patch = mpatches.Circle(xy=center,
                        radius=radius,
                        # COMMON OPTIONS:
                        alpha=alpha,
                        fill=fill,
                        facecolor=fill_color,
                        hatch=fill_pattern,
                        ec=line_color,
                        lw=line_width,
                        linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.Circle", fontsize=TITLE_FONT_SIZE)

# DRAW AN ELLIPSE #############################################################

ax = axs[next(it)]

center = (0., 0.)         # center of the circle
width = 8
height = 6
angle = 0.

patch = mpatches.Ellipse(xy=center,
                         width=width,
                         height=height,
                         angle=angle,
                         # COMMON OPTIONS:
                         alpha=alpha,
                         fill=fill,
                         facecolor=fill_color,
                         hatch=fill_pattern,
                         ec=line_color,
                         lw=line_width,
                         linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.Ellipse", fontsize=TITLE_FONT_SIZE)

# DRAW A WEDGE ################################################################

ax = axs[next(it)]

center = (0., 0.)         # center of the circle
radius = 3.
theta1 = -125.
theta2 = 125.
width = None

patch = mpatches.Wedge(center=center,
                       r=radius,
                       theta1=theta1,
                       theta2=theta2,
                       width=width,
                       # COMMON OPTIONS:
                       alpha=alpha,
                       fill=fill,
                       facecolor=fill_color,
                       hatch=fill_pattern,
                       ec=line_color,
                       lw=line_width,
                       joinstyle=join_style,
                       linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.Wedge\n(width=None)", fontsize=TITLE_FONT_SIZE)

# DRAW A WEDGE ################################################################

ax = axs[next(it)]

center = (0., 0.)         # center of the circle
radius = 3.
theta1 = -125.
theta2 = 125.
width = 1.

patch = mpatches.Wedge(center=center,
                       r=radius,
                       theta1=theta1,
                       theta2=theta2,
                       width=width,
                       # COMMON OPTIONS:
                       alpha=alpha,
                       fill=fill,
                       facecolor=fill_color,
                       hatch=fill_pattern,
                       ec=line_color,
                       lw=line_width,
                       joinstyle=join_style,
                       linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.Wedge\n(width=1)", fontsize=TITLE_FONT_SIZE)

# DRAW AN ARC #################################################################

ax = axs[next(it)]

center = (0., 0.)         # center of ellipse
width = 4.                # length of horizontal axis
height = 2.               # length of vertical axis
rotation = 45.            # rotation in degrees (anti-clockwise)
start_angle = -125.       # starting angle of the arc in degrees
end_angle = 95.           # ending angle of the arc in degrees

patch = mpatches.Arc(xy=center,
                     width=width,
                     height=height,
                     angle=rotation,
                     theta1=start_angle,
                     theta2=end_angle,
                     # COMMON OPTIONS:
                     alpha=alpha,
                     hatch=fill_pattern,
                     ec=line_color,
                     lw=line_width,
                     joinstyle=join_style,
                     linestyle=line_style)

ax.add_patch(patch)
ax.set_title("matplotlib.patches.Arc", fontsize=TITLE_FONT_SIZE)

# DRAW A PATH PATCH ###########################################################

# See: https://matplotlib.org/api/path_api.html#module-matplotlib.path

ax = axs[next(it)]

path = mpath.Path
path_data = [
                (path.MOVETO, (1.58, -2.57)),
                (path.CURVE4, (0.35, -1.1)),
                (path.CURVE4, (-1.75, 2.0)),
                (path.CURVE4, (0.375, 2.0)),
                (path.LINETO, (0.85, 1.15)),
                (path.CURVE4, (2.2, 3.2)),
                (path.CURVE4, (3, 0.05)),
                (path.CURVE4, (2.0, -0.5)),
                (path.CLOSEPOLY, (1.58, -2.57)),
            ]

codes, verts = zip(*path_data)

path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path,
                           # COMMON OPTIONS:
                           alpha=alpha,
                           fill=fill,
                           facecolor=fill_color,
                           hatch=fill_pattern,
                           ec=line_color,
                           lw=line_width,
                           joinstyle=join_style,
                           linestyle=line_style)

ax.add_patch(patch)

# plot control points and connecting lines

x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-', alpha=0.5, markersize=3)

ax.set_title("matplotlib.patches.Path", fontsize=TITLE_FONT_SIZE)


# DISPLAY TEXT ################################################################

ax = axs[next(it)]

line = mlines.Line2D((-1, 1), (0, 0), alpha=0.5, lw=1, linestyle="dotted", color="green")
ax.add_line(line)

line = mlines.Line2D((0, 0), (-1, 1), alpha=0.5, lw=1, linestyle="dotted", color="green")
ax.add_line(line)

text = "Hello"
fontsize = 32.
with_dash = False

ax.text(x=0.,
        y=0.,
        s=text,
        fontsize=fontsize,
        alpha=alpha,
        color="blue",
        horizontalalignment='center',
        verticalalignment='center',
        withdash=with_dash)

ax.set_title("Axes.text", fontsize=TITLE_FONT_SIZE)

# SAVE FILE ###################################################################

plt.tight_layout()
#plt.savefig("draw_geometric_shapes.png")

# DISPLAY FIGURES #############################################################

plt.show()
In [14]:
import numpy as np
import matplotlib.pyplot as plt

# Build datas ###############

x = np.arange(6)
y = x
y_err = y / 2.

# Plot data #################

plt.errorbar(x, y, yerr=y_err, fmt='-o')

# Save file and plot ########

#plt.savefig("error_bar.png")
plt.show()
In [15]:
import numpy as np
import matplotlib.pyplot as plt

# Build datas ###############

x = np.arange(0, 10, 0.05)
y1 = np.cos(x)
y2 = np.sin(x)

# Plot data #################

plt.plot(x, y1, x, y2)
plt.fill_between(x, y1, y2, facecolor='red', alpha=0.5)

# Save file and plot ########

#plt.savefig("fill.png")
plt.show()
In [16]:
import math
import numpy as np
import matplotlib.pyplot as plt

from matplotlib.finance import quotes_historical_yahoo_ohlc
import datetime

date1 = datetime.date( 1995, 1, 1 ) 
date2 = datetime.date( 2004, 4, 12 )
quotes = quotes_historical_yahoo_ohlc('INTC', date1, date2)

opens = [q[1] for q in quotes]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(opens)

# SAVE FILES ######################
#plt.savefig("finance_yahoo_dataset.png")

plt.show()
/Users/jdecock/anaconda/lib/python3.5/site-packages/matplotlib/cbook.py:136: MatplotlibDeprecationWarning: The finance module has been deprecated in mpl 2.0 and will be removed in mpl 2.2. Please use the module mpl_finance instead.
  warnings.warn(message, mplDeprecation, stacklevel=1)
In [17]:
import numpy as np
import matplotlib.pyplot as plt

# Build datas ###############

x = np.arange(-10, 10, 0.01)
y = np.sin(2. * 2. * np.pi * x) * 1. / np.sqrt(2. * np.pi) * np.exp(-(x**2.)/2.)

# Plot data #################

with plt.xkcd():                        # <- Set XKCD style
    fig = plt.figure(figsize=(6., 6.))
    ax = fig.add_subplot(111)

    ax.plot(x, y, "-", label="Test")

    # Set title and labels ######

    ax.set_title(r"Test", fontsize=20)
    ax.set_xlabel(r"$x$", fontsize=32)
    ax.set_ylabel(r"$f(x)$", fontsize=32)

    # Set legend ################

    ax.legend(loc='lower right', fontsize=20)

# Save file #################

plt.tight_layout()
#plt.savefig("hand_drawn_like_style.png")

# Plot ######################

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

# SETUP #######################################################################

# histtype : [‘bar’ | ‘barstacked’ | ‘step’ | ‘stepfilled’]
HIST_TYPE='bar'
ALPHA=0.5

# MAKE DATA ###################################################################

gaussian_numbers_list_1 = np.random.normal(size=1000)
gaussian_numbers_list_2 = np.random.normal(size=500)
gaussian_numbers_list_3 = np.random.normal(size=500)

# INIT FIGURE #################################################################

fig = plt.figure(figsize=(16.0, 9.0))

ax1 = fig.add_subplot(411)
ax2 = fig.add_subplot(412)
ax3 = fig.add_subplot(413)
ax4 = fig.add_subplot(414)

# AX1 #########################################################################

res_tuple = ax1.hist(gaussian_numbers_list_1,
                     histtype=HIST_TYPE,
                     alpha=ALPHA)

print(res_tuple)

res_tuple = ax1.hist(gaussian_numbers_list_1,
                     bins=35,
                     histtype=HIST_TYPE,
                     alpha=ALPHA)

ax1.set_xlabel("value")
ax1.set_ylabel("frequency")
print(res_tuple)

# AX2 #########################################################################

# Create a histogram by providing the bin edges (equally spaced here)
bins = [-4.0, -3.5, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]

res_tuple = ax2.hist(gaussian_numbers_list_1,
                     bins=bins,
                     histtype=HIST_TYPE)

ax2.set_xlabel("value")
ax2.set_ylabel("frequency")
print(res_tuple)

# AX3 #########################################################################

res_tuple = ax3.hist(gaussian_numbers_list_1,
                     bins=30,
                     histtype=HIST_TYPE,
                     normed=True,
                     cumulative=True)

ax3.set_ylim([0., 1.])
ax3.set_xlabel("value")
ax3.set_ylabel("probability")
print(res_tuple)

# AX4 #########################################################################

res_tuple = ax4.hist([gaussian_numbers_list_1, gaussian_numbers_list_2, gaussian_numbers_list_3],
                     bins=30,
                     histtype=HIST_TYPE)

ax4.set_xlabel("value")
ax4.set_ylabel("frequency")
print(res_tuple)

# SHOW AND SAVE FILE ##########################################################

plt.tight_layout()

#plt.savefig("hist.png")
plt.show()
(array([   5.,   19.,   68.,  164.,  238.,  232.,  169.,   73.,   30.,    2.]), array([-3.46470298, -2.77860084, -2.09249871, -1.40639657, -0.72029443,
       -0.0341923 ,  0.65190984,  1.33801198,  2.02411411,  2.71021625,
        3.39631839]), <a list of 10 Patch objects>)
(array([  3.,   0.,   1.,   3.,   2.,   2.,  13.,  14.,  21.,  21.,  26.,
        27.,  60.,  63.,  63.,  77.,  66.,  71.,  72.,  63.,  58.,  65.,
        44.,  42.,  38.,  24.,  19.,  10.,  10.,   8.,  11.,   1.,   1.,
         0.,   1.]), array([-3.46470298, -3.2686738 , -3.07264462, -2.87661544, -2.68058625,
       -2.48455707, -2.28852789, -2.09249871, -1.89646953, -1.70044034,
       -1.50441116, -1.30838198, -1.1123528 , -0.91632362, -0.72029443,
       -0.52426525, -0.32823607, -0.13220689,  0.06382229,  0.25985148,
        0.45588066,  0.65190984,  0.84793902,  1.0439682 ,  1.23999739,
        1.43602657,  1.63205575,  1.82808493,  2.02411411,  2.2201433 ,
        2.41617248,  2.61220166,  2.80823084,  3.00426002,  3.20028921,
        3.39631839]), <a list of 35 Patch objects>)
(array([   0.,    3.,    6.,   23.,   48.,   82.,  168.,  175.,  175.,
        144.,   95.,   47.,   25.,    8.,    1.,    0.]), array([-4. , -3.5, -3. , -2.5, -2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,
        1.5,  2. ,  2.5,  3. ,  3.5,  4. ]), <a list of 16 Patch objects>)
(array([ 0.003,  0.003,  0.005,  0.008,  0.01 ,  0.024,  0.044,  0.062,
        0.092,  0.124,  0.185,  0.256,  0.335,  0.416,  0.494,  0.587,
        0.655,  0.726,  0.8  ,  0.853,  0.895,  0.929,  0.953,  0.968,
        0.981,  0.99 ,  0.998,  0.999,  0.999,  1.   ]), array([-3.46470298, -3.23600227, -3.00730156, -2.77860084, -2.54990013,
       -2.32119942, -2.09249871, -1.863798  , -1.63509728, -1.40639657,
       -1.17769586, -0.94899515, -0.72029443, -0.49159372, -0.26289301,
       -0.0341923 ,  0.19450842,  0.42320913,  0.65190984,  0.88061055,
        1.10931127,  1.33801198,  1.56671269,  1.7954134 ,  2.02411411,
        2.25281483,  2.48151554,  2.71021625,  2.93891696,  3.16761768,
        3.39631839]), <a list of 30 Patch objects>)
([array([  3.,   0.,   2.,   3.,   2.,  14.,  20.,  18.,  30.,  32.,  61.,
        71.,  79.,  81.,  78.,  93.,  68.,  71.,  74.,  53.,  42.,  34.,
        24.,  15.,  13.,   9.,   8.,   1.,   0.,   1.]), array([  0.,   0.,   0.,   0.,   0.,   3.,   7.,  10.,  17.,  16.,  25.,
        28.,  30.,  39.,  44.,  65.,  37.,  44.,  37.,  27.,  28.,  13.,
        15.,   6.,   2.,   3.,   1.,   2.,   0.,   1.]), array([  1.,   0.,   0.,   1.,   3.,   1.,   7.,   8.,  14.,  17.,  30.,
        32.,  39.,  50.,  38.,  63.,  34.,  39.,  30.,  24.,  23.,  18.,
         7.,  10.,   8.,   1.,   1.,   0.,   1.,   0.])], array([-3.46470298, -3.23600227, -3.00730156, -2.77860084, -2.54990013,
       -2.32119942, -2.09249871, -1.863798  , -1.63509728, -1.40639657,
       -1.17769586, -0.94899515, -0.72029443, -0.49159372, -0.26289301,
       -0.0341923 ,  0.19450842,  0.42320913,  0.65190984,  0.88061055,
        1.10931127,  1.33801198,  1.56671269,  1.7954134 ,  2.02411411,
        2.25281483,  2.48151554,  2.71021625,  2.93891696,  3.16761768,
        3.39631839]), <a list of 3 Lists of Patches objects>)
In [19]:
import numpy as np
import matplotlib.pyplot as plt

# MAKE DATA ###################################################################

x, y = np.random.normal(size=(2, 100000))

# INIT FIGURE #################################################################

fig = plt.figure(figsize=(8.0, 8.0))
ax = fig.add_subplot(111)

# AX ##########################################################################

H = ax.hist2d(x, y, bins=40)
fig.colorbar(H[3], ax=ax)

# SHOW AND SAVE FILE ##########################################################

plt.tight_layout()

#plt.savefig("hist2d.png")
plt.show()
In [20]:
import numpy as np
import matplotlib.pyplot as plt

# MAKE DATA ###################################################################

x, y = np.random.normal(size=(2, 100000))

# INIT FIGURE #################################################################

fig = plt.figure(figsize=(8.0, 8.0))
ax = fig.add_subplot(111)

# AX ##########################################################################

im = ax.hexbin(x, y, gridsize=40)
fig.colorbar(im, ax=ax)

# SHOW AND SAVE FILE ##########################################################

plt.tight_layout()

#plt.savefig("hist2d_hexa.png")
plt.show()

Make a 2D histogram using a hexagonal binning and a logarithmic scale on X and Y axis

Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/hist2d_hexa_logscale_xy.py

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

# MAKE DATA ###################################################################

x, y = np.random.exponential(size=(2, 100000))

# INIT FIGURE #################################################################

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))

# AX1 #########################################################################

im = ax1.hexbin(x, y, gridsize=40)
fig.colorbar(im, ax=ax1)

ax1.set_title("Normal scale")

# AX2 #########################################################################

x = np.log10(x)
y = np.log10(y)

im = ax2.hexbin(x, y, gridsize=40)
fig.colorbar(im, ax=ax2)

# Use "10^n" instead "n" as ticks label
func_formatter = lambda x, pos: r'$10^{{{}}}$'.format(int(x))
ax2.xaxis.set_major_formatter(FuncFormatter(func_formatter))
ax2.yaxis.set_major_formatter(FuncFormatter(func_formatter))

ax2.set_title("Log scale")

# SHOW AND SAVE FILE ##########################################################

plt.tight_layout()

#plt.savefig("hist2d_hexa_logscale_xy.png")
plt.show()