Jérémie Decock (www.jdhp.org)
This document has been made from JDHP.org snippets using https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/make_notebook.py
Last update: 2017-07-20
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/ax_set_label.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/ax_set_legend.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/ax_set_title.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/ax_set_xylim.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/axis_equal.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/bar.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/colour_map_list.py
See: http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
See also:
import matplotlib.pyplot as plt
# Get a list of the colormaps in matplotlib.
maps = sorted(plt.cm.datad)
print(maps)
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/contour.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/contour_from_hist2d.py
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()
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/draw_geometric_shapes.py
See:
TODO:
Fancy Arrows:
Text with Fancy Box:
Path Patch: https://matplotlib.org/api/path_api.html#module-matplotlib.path
Transform:
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/error_bar.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/fill.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/finance_yahoo_dataset.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/hand_drawn_like_style.py
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/hist.py
See:
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()
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/hist2d_hexa.py
See:
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()
Source: https://github.com/jeremiedecock/snippets/blob/master/python/matplotlib/hist2d_hexa_logscale_xy.py
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()