image imagewidth (px) 75 2.22k | code stringlengths 300 16.2k | example_id stringlengths 28 79 | figure_index int64 0 26 | figure_name stringclasses 28
values | title stringlengths 38 94 | example_page_url stringlengths 61 195 | source_url stringlengths 80 111 | source_relpath stringlengths 6 37 | category_hint stringclasses 24
values | status stringclasses 1
value | num_figures int64 1 27 | error null |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
"""
========================
Anchored Direction Arrow
========================
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as fm
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDirectionArrows
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.imshow(np.random.random((10, 10)))
# Simple example
simple_arrow = AnchoredDirectionArrows(ax.transAxes, 'X', 'Y')
ax.add_artist(simple_arrow)
# High contrast arrow
high_contrast_part_1 = AnchoredDirectionArrows(
ax.transAxes,
'111', r'11$\overline{2}$',
loc='upper right',
arrow_props={'ec': 'w', 'fc': 'none', 'alpha': 1,
'lw': 2}
)
ax.add_artist(high_contrast_part_1)
high_contrast_part_2 = AnchoredDirectionArrows(
ax.transAxes,
'111', r'11$\overline{2}$',
loc='upper right',
arrow_props={'ec': 'none', 'fc': 'k'},
text_props={'ec': 'w', 'fc': 'k', 'lw': 0.4}
)
ax.add_artist(high_contrast_part_2)
# Rotated arrow
fontprops = fm.FontProperties(family='serif')
rotated_arrow = AnchoredDirectionArrows(
ax.transAxes,
'30', '120',
loc='center',
color='w',
angle=30,
fontproperties=fontprops
)
ax.add_artist(rotated_arrow)
# Altering arrow directions
a1 = AnchoredDirectionArrows(
ax.transAxes, 'A', 'B', loc='lower center',
length=-0.15,
sep_x=0.03, sep_y=0.03,
color='r'
)
ax.add_artist(a1)
a2 = AnchoredDirectionArrows(
ax.transAxes, 'A', ' B', loc='lower left',
aspect_ratio=-1,
sep_x=0.01, sep_y=-0.02,
color='orange'
)
ax.add_artist(a2)
a3 = AnchoredDirectionArrows(
ax.transAxes, ' A', 'B', loc='lower right',
length=-0.15,
aspect_ratio=-1,
sep_y=-0.1, sep_x=0.04,
color='cyan'
)
ax.add_artist(a3)
plt.show()
| stable__gallery__axes_grid1__demo_anchored_direction_arrows | 0 | figure_000.png | Anchored Direction Arrow — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_anchored_direction_arrows.html#sphx-glr-download-gallery-axes-grid1-demo-anchored-direction-arrows-py | https://matplotlib.org/stable/_downloads/82ac862070a073a69fc9b974db5ab46b/demo_anchored_direction_arrows.py | demo_anchored_direction_arrows.py | axes_grid1 | ok | 1 | null | |
"""
============
Axes divider
============
Axes divider to calculate location of Axes and
create a divider for them using existing Axes instances.
"""
import matplotlib.pyplot as plt
from matplotlib import cbook
def get_demo_image():
z = cbook.get_sample_data("axes_grid/bivariate_normal.npy") # 15x15 array
return z, (-3, 4, -4, 3)
def demo_simple_image(ax):
Z, extent = get_demo_image()
im = ax.imshow(Z, extent=extent)
cb = plt.colorbar(im)
cb.ax.yaxis.set_tick_params(labelright=False)
def demo_locatable_axes_hard(fig):
from mpl_toolkits.axes_grid1 import Size, SubplotDivider
divider = SubplotDivider(fig, 2, 2, 2, aspect=True)
# Axes for image
ax = fig.add_subplot(axes_locator=divider.new_locator(nx=0, ny=0))
# Axes for colorbar
ax_cb = fig.add_subplot(axes_locator=divider.new_locator(nx=2, ny=0))
divider.set_horizontal([
Size.AxesX(ax), # main Axes
Size.Fixed(0.05), # padding, 0.1 inch
Size.Fixed(0.2), # colorbar, 0.3 inch
])
divider.set_vertical([Size.AxesY(ax)])
Z, extent = get_demo_image()
im = ax.imshow(Z, extent=extent)
plt.colorbar(im, cax=ax_cb)
ax_cb.yaxis.set_tick_params(labelright=False)
def demo_locatable_axes_easy(ax):
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
ax_cb = divider.append_axes("right", size="5%", pad=0.05)
fig = ax.get_figure()
fig.add_axes(ax_cb)
Z, extent = get_demo_image()
im = ax.imshow(Z, extent=extent)
plt.colorbar(im, cax=ax_cb)
ax_cb.yaxis.tick_right()
ax_cb.yaxis.set_tick_params(labelright=False)
def demo_images_side_by_side(ax):
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
Z, extent = get_demo_image()
ax2 = divider.append_axes("right", size="100%", pad=0.05)
fig1 = ax.get_figure()
fig1.add_axes(ax2)
ax.imshow(Z, extent=extent)
ax2.imshow(Z, extent=extent)
ax2.yaxis.set_tick_params(labelleft=False)
def demo():
fig = plt.figure(figsize=(6, 6))
# PLOT 1
# simple image & colorbar
ax = fig.add_subplot(2, 2, 1)
demo_simple_image(ax)
# PLOT 2
# image and colorbar with draw-time positioning -- a hard way
demo_locatable_axes_hard(fig)
# PLOT 3
# image and colorbar with draw-time positioning -- an easy way
ax = fig.add_subplot(2, 2, 3)
demo_locatable_axes_easy(ax)
# PLOT 4
# two images side by side with fixed padding.
ax = fig.add_subplot(2, 2, 4)
demo_images_side_by_side(ax)
plt.show()
demo()
| stable__gallery__axes_grid1__demo_axes_divider | 0 | figure_000.png | Axes divider — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_axes_divider.html#sphx-glr-download-gallery-axes-grid1-demo-axes-divider-py | https://matplotlib.org/stable/_downloads/52e9d9c67d12b0707ec2ebfda10937f5/demo_axes_divider.py | demo_axes_divider.py | axes_grid1 | ok | 1 | null | |
"""
==============
Demo Axes Grid
==============
Grid of 2x2 images with a single colorbar or with one colorbar per Axes.
"""
import matplotlib.pyplot as plt
from matplotlib import cbook
from mpl_toolkits.axes_grid1 import ImageGrid
fig = plt.figure(figsize=(10.5, 2.5))
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy") # 15x15 array
extent = (-3, 4, -4, 3)
# A grid of 2x2 images with 0.05 inch pad between images and only the
# lower-left Axes is labeled.
grid = ImageGrid(
fig, 141, # similar to fig.add_subplot(141).
nrows_ncols=(2, 2), axes_pad=0.05, label_mode="1")
for ax in grid:
ax.imshow(Z, extent=extent)
# This only affects Axes in first column and second row as share_all=False.
grid.axes_llc.set(xticks=[-2, 0, 2], yticks=[-2, 0, 2])
# A grid of 2x2 images with a single colorbar.
grid = ImageGrid(
fig, 142, # similar to fig.add_subplot(142).
nrows_ncols=(2, 2), axes_pad=0.0, label_mode="L", share_all=True,
cbar_location="top", cbar_mode="single")
for ax in grid:
im = ax.imshow(Z, extent=extent)
grid.cbar_axes[0].colorbar(im)
for cax in grid.cbar_axes:
cax.tick_params(labeltop=False)
# This affects all Axes as share_all = True.
grid.axes_llc.set(xticks=[-2, 0, 2], yticks=[-2, 0, 2])
# A grid of 2x2 images. Each image has its own colorbar.
grid = ImageGrid(
fig, 143, # similar to fig.add_subplot(143).
nrows_ncols=(2, 2), axes_pad=0.1, label_mode="1", share_all=True,
cbar_location="top", cbar_mode="each", cbar_size="7%", cbar_pad="2%")
for ax, cax in zip(grid, grid.cbar_axes):
im = ax.imshow(Z, extent=extent)
cax.colorbar(im)
cax.tick_params(labeltop=False)
# This affects all Axes as share_all = True.
grid.axes_llc.set(xticks=[-2, 0, 2], yticks=[-2, 0, 2])
# A grid of 2x2 images. Each image has its own colorbar.
grid = ImageGrid(
fig, 144, # similar to fig.add_subplot(144).
nrows_ncols=(2, 2), axes_pad=(0.45, 0.15), label_mode="1", share_all=True,
cbar_location="right", cbar_mode="each", cbar_size="7%", cbar_pad="2%")
# Use a different colorbar range every time
limits = ((0, 1), (-2, 2), (-1.7, 1.4), (-1.5, 1))
for ax, cax, vlim in zip(grid, grid.cbar_axes, limits):
im = ax.imshow(Z, extent=extent, vmin=vlim[0], vmax=vlim[1])
cb = cax.colorbar(im)
cb.set_ticks((vlim[0], vlim[1]))
# This affects all Axes as share_all = True.
grid.axes_llc.set(xticks=[-2, 0, 2], yticks=[-2, 0, 2])
plt.show()
| stable__gallery__axes_grid1__demo_axes_grid | 0 | figure_000.png | Demo Axes Grid — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_axes_grid.html#sphx-glr-download-gallery-axes-grid1-demo-axes-grid-py | https://matplotlib.org/stable/_downloads/e59c7fc1ea02b23c213a2688aba898cc/demo_axes_grid.py | demo_axes_grid.py | axes_grid1 | ok | 1 | null | |
"""
==========
Axes Grid2
==========
Grid of images with shared xaxis and yaxis.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook
from mpl_toolkits.axes_grid1 import ImageGrid
def add_inner_title(ax, title, loc, **kwargs):
from matplotlib.offsetbox import AnchoredText
from matplotlib.patheffects import withStroke
prop = dict(path_effects=[withStroke(foreground='w', linewidth=3)],
size=plt.rcParams['legend.fontsize'])
at = AnchoredText(title, loc=loc, prop=prop,
pad=0., borderpad=0.5,
frameon=False, **kwargs)
ax.add_artist(at)
return at
fig = plt.figure(figsize=(6, 6))
# Prepare images
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")
extent = (-3, 4, -4, 3)
ZS = [Z[i::3, :] for i in range(3)]
extent = extent[0], extent[1]/3., extent[2], extent[3]
# *** Demo 1: colorbar at each Axes ***
grid = ImageGrid(
# 211 = at the position of fig.add_subplot(211)
fig, 211, nrows_ncols=(1, 3), axes_pad=0.05, label_mode="1", share_all=True,
cbar_location="top", cbar_mode="each", cbar_size="7%", cbar_pad="1%")
grid[0].set(xticks=[-2, 0], yticks=[-2, 0, 2])
for i, (ax, z) in enumerate(zip(grid, ZS)):
im = ax.imshow(z, origin="lower", extent=extent)
cb = ax.cax.colorbar(im)
# Changing the colorbar ticks
if i in [1, 2]:
cb.set_ticks([-1, 0, 1])
for ax, im_title in zip(grid, ["Image 1", "Image 2", "Image 3"]):
add_inner_title(ax, im_title, loc='lower left')
# *** Demo 2: shared colorbar ***
grid2 = ImageGrid(
fig, 212, nrows_ncols=(1, 3), axes_pad=0.05, label_mode="1", share_all=True,
cbar_location="right", cbar_mode="single", cbar_size="10%", cbar_pad=0.05)
grid2[0].set(xlabel="X", ylabel="Y", xticks=[-2, 0], yticks=[-2, 0, 2])
clim = (np.min(ZS), np.max(ZS))
for ax, z in zip(grid2, ZS):
im = ax.imshow(z, clim=clim, origin="lower", extent=extent)
# With cbar_mode="single", cax attribute of all Axes are identical.
ax.cax.colorbar(im)
for ax, im_title in zip(grid2, ["(a)", "(b)", "(c)"]):
add_inner_title(ax, im_title, loc='upper left')
plt.show()
| stable__gallery__axes_grid1__demo_axes_grid2 | 0 | figure_000.png | Axes Grid2 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_axes_grid2.html#sphx-glr-download-gallery-axes-grid1-demo-axes-grid2-py | https://matplotlib.org/stable/_downloads/5fc19bc53f353b5d6f24bdca17a4c140/demo_axes_grid2.py | demo_axes_grid2.py | axes_grid1 | ok | 1 | null | |
"""
================================
HBoxDivider and VBoxDivider demo
================================
Using an `.HBoxDivider` to arrange subplots.
Note that both Axes' location are adjusted so that they have
equal heights while maintaining their aspect ratios.
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider, VBoxDivider
import mpl_toolkits.axes_grid1.axes_size as Size
arr1 = np.arange(20).reshape((4, 5))
arr2 = np.arange(20).reshape((5, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(arr1)
ax2.imshow(arr2)
pad = 0.5 # pad in inches
divider = HBoxDivider(
fig, 111,
horizontal=[Size.AxesX(ax1), Size.Fixed(pad), Size.AxesX(ax2)],
vertical=[Size.AxesY(ax1), Size.Scaled(1), Size.AxesY(ax2)])
ax1.set_axes_locator(divider.new_locator(0))
ax2.set_axes_locator(divider.new_locator(2))
plt.show()
# %%
# Using a `.VBoxDivider` to arrange subplots.
#
# Note that both Axes' location are adjusted so that they have
# equal widths while maintaining their aspect ratios.
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.imshow(arr1)
ax2.imshow(arr2)
divider = VBoxDivider(
fig, 111,
horizontal=[Size.AxesX(ax1), Size.Scaled(1), Size.AxesX(ax2)],
vertical=[Size.AxesY(ax1), Size.Fixed(pad), Size.AxesY(ax2)])
ax1.set_axes_locator(divider.new_locator(0))
ax2.set_axes_locator(divider.new_locator(2))
plt.show()
| stable__gallery__axes_grid1__demo_axes_hbox_divider | 0 | figure_000.png | HBoxDivider and VBoxDivider demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_axes_hbox_divider.html#sphx-glr-download-gallery-axes-grid1-demo-axes-hbox-divider-py | https://matplotlib.org/stable/_downloads/d068f88cea39314c1b79c61e63f18720/demo_axes_hbox_divider.py | demo_axes_hbox_divider.py | axes_grid1 | ok | 2 | null | |
"""
===============================
Show RGB channels using RGBAxes
===============================
`~.axes_grid1.axes_rgb.RGBAxes` creates a layout of 4 Axes for displaying RGB
channels: one large Axes for the RGB image and 3 smaller Axes for the R, G, B
channels.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook
from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes, make_rgb_axes
def get_rgb():
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")
Z[Z < 0] = 0.
Z = Z / Z.max()
R = Z[:13, :13]
G = Z[2:, 2:]
B = Z[:13, 2:]
return R, G, B
def make_cube(r, g, b):
ny, nx = r.shape
R = np.zeros((ny, nx, 3))
R[:, :, 0] = r
G = np.zeros_like(R)
G[:, :, 1] = g
B = np.zeros_like(R)
B[:, :, 2] = b
RGB = R + G + B
return R, G, B, RGB
def demo_rgb1():
fig = plt.figure()
ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8], pad=0.0)
r, g, b = get_rgb()
ax.imshow_rgb(r, g, b)
def demo_rgb2():
fig, ax = plt.subplots()
ax_r, ax_g, ax_b = make_rgb_axes(ax, pad=0.02)
r, g, b = get_rgb()
im_r, im_g, im_b, im_rgb = make_cube(r, g, b)
ax.imshow(im_rgb)
ax_r.imshow(im_r)
ax_g.imshow(im_g)
ax_b.imshow(im_b)
for ax in fig.axes:
ax.tick_params(direction='in', color='w')
ax.spines[:].set_color("w")
demo_rgb1()
demo_rgb2()
plt.show()
| stable__gallery__axes_grid1__demo_axes_rgb | 0 | figure_000.png | Show RGB channels using RGBAxes — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_axes_rgb.html#sphx-glr-download-gallery-axes-grid1-demo-axes-rgb-py | https://matplotlib.org/stable/_downloads/d4f8e826c13bbb870ffee065e8625f5d/demo_axes_rgb.py | demo_axes_rgb.py | axes_grid1 | ok | 2 | null | |
"""
===============================
Show RGB channels using RGBAxes
===============================
`~.axes_grid1.axes_rgb.RGBAxes` creates a layout of 4 Axes for displaying RGB
channels: one large Axes for the RGB image and 3 smaller Axes for the R, G, B
channels.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook
from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes, make_rgb_axes
def get_rgb():
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")
Z[Z < 0] = 0.
Z = Z / Z.max()
R = Z[:13, :13]
G = Z[2:, 2:]
B = Z[:13, 2:]
return R, G, B
def make_cube(r, g, b):
ny, nx = r.shape
R = np.zeros((ny, nx, 3))
R[:, :, 0] = r
G = np.zeros_like(R)
G[:, :, 1] = g
B = np.zeros_like(R)
B[:, :, 2] = b
RGB = R + G + B
return R, G, B, RGB
def demo_rgb1():
fig = plt.figure()
ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8], pad=0.0)
r, g, b = get_rgb()
ax.imshow_rgb(r, g, b)
def demo_rgb2():
fig, ax = plt.subplots()
ax_r, ax_g, ax_b = make_rgb_axes(ax, pad=0.02)
r, g, b = get_rgb()
im_r, im_g, im_b, im_rgb = make_cube(r, g, b)
ax.imshow(im_rgb)
ax_r.imshow(im_r)
ax_g.imshow(im_g)
ax_b.imshow(im_b)
for ax in fig.axes:
ax.tick_params(direction='in', color='w')
ax.spines[:].set_color("w")
demo_rgb1()
demo_rgb2()
plt.show()
| stable__gallery__axes_grid1__demo_axes_rgb | 1 | figure_001.png | Show RGB channels using RGBAxes — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_axes_rgb.html#sphx-glr-download-gallery-axes-grid1-demo-axes-rgb-py | https://matplotlib.org/stable/_downloads/d4f8e826c13bbb870ffee065e8625f5d/demo_axes_rgb.py | demo_axes_rgb.py | axes_grid1 | ok | 2 | null | |
"""
.. _demo-colorbar-with-axes-divider:
=========================
Colorbar with AxesDivider
=========================
The `.axes_divider.make_axes_locatable` function takes an existing Axes, adds
it to a new `.AxesDivider` and returns the `.AxesDivider`. The `.append_axes`
method of the `.AxesDivider` can then be used to create a new Axes on a given
side ("top", "right", "bottom", or "left") of the original Axes. This example
uses `.append_axes` to add colorbars next to Axes.
Users should consider simply passing the main Axes to the *ax* keyword argument of
`~.Figure.colorbar` instead of creating a locatable Axes manually like this.
See :ref:`colorbar_placement`.
.. redirect-from:: /gallery/axes_grid1/simple_colorbar
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.subplots_adjust(wspace=0.5)
im1 = ax1.imshow([[1, 2], [3, 4]])
ax1_divider = make_axes_locatable(ax1)
# Add an Axes to the right of the main Axes.
cax1 = ax1_divider.append_axes("right", size="7%", pad="2%")
cb1 = fig.colorbar(im1, cax=cax1)
im2 = ax2.imshow([[1, 2], [3, 4]])
ax2_divider = make_axes_locatable(ax2)
# Add an Axes above the main Axes.
cax2 = ax2_divider.append_axes("top", size="7%", pad="2%")
cb2 = fig.colorbar(im2, cax=cax2, orientation="horizontal")
# Change tick position to top (with the default tick position "bottom", ticks
# overlap the image).
cax2.xaxis.set_ticks_position("top")
plt.show()
| stable__gallery__axes_grid1__demo_colorbar_with_axes_divider | 0 | figure_000.png | Colorbar with AxesDivider — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_colorbar_with_axes_divider.html#sphx-glr-download-gallery-axes-grid1-demo-colorbar-with-axes-divider-py | https://matplotlib.org/stable/_downloads/cec7ab65767ff5217c21ae213755cda8/demo_colorbar_with_axes_divider.py | demo_colorbar_with_axes_divider.py | axes_grid1 | ok | 1 | null | |
"""
.. _demo-colorbar-with-inset-locator:
===========================================================
Control the position and size of a colorbar with Inset Axes
===========================================================
This example shows how to control the position, height, and width of colorbars
using `~mpl_toolkits.axes_grid1.inset_locator.inset_axes`.
Inset Axes placement is controlled as for legends: either by providing a *loc*
option ("upper right", "best", ...), or by providing a locator with respect to
the parent bbox. Parameters such as *bbox_to_anchor* and *borderpad* likewise
work in the same way, and are also demonstrated here.
Users should consider using `.Axes.inset_axes` instead (see
:ref:`colorbar_placement`).
.. redirect-from:: /gallery/axes_grid1/demo_colorbar_of_inset_axes
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=[6, 3])
im1 = ax1.imshow([[1, 2], [2, 3]])
axins1 = inset_axes(
ax1,
width="50%", # width: 50% of parent_bbox width
height="5%", # height: 5%
loc="upper right",
)
axins1.xaxis.set_ticks_position("bottom")
fig.colorbar(im1, cax=axins1, orientation="horizontal", ticks=[1, 2, 3])
im = ax2.imshow([[1, 2], [2, 3]])
axins = inset_axes(
ax2,
width="5%", # width: 5% of parent_bbox width
height="50%", # height: 50%
loc="lower left",
bbox_to_anchor=(1.05, 0., 1, 1),
bbox_transform=ax2.transAxes,
borderpad=0,
)
fig.colorbar(im, cax=axins, ticks=[1, 2, 3])
plt.show()
| stable__gallery__axes_grid1__demo_colorbar_with_inset_locator | 0 | figure_000.png | Control the position and size of a colorbar with Inset Axes — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_colorbar_with_inset_locator.html#sphx-glr-download-gallery-axes-grid1-demo-colorbar-with-inset-locator-py | https://matplotlib.org/stable/_downloads/fef8ebea91f3e2d936a0356c1b573cd8/demo_colorbar_with_inset_locator.py | demo_colorbar_with_inset_locator.py | axes_grid1 | ok | 1 | null | |
"""
===============================
Per-row or per-column colorbars
===============================
This example shows how to use one common colorbar for each row or column
of an image grid.
"""
import matplotlib.pyplot as plt
from matplotlib import cbook
from mpl_toolkits.axes_grid1 import AxesGrid
def get_demo_image():
z = cbook.get_sample_data("axes_grid/bivariate_normal.npy") # 15x15 array
return z, (-3, 4, -4, 3)
def demo_bottom_cbar(fig):
"""
A grid of 2x2 images with a colorbar for each column.
"""
grid = AxesGrid(fig, 121, # similar to subplot(121)
nrows_ncols=(2, 2),
axes_pad=0.10,
share_all=True,
label_mode="1",
cbar_location="bottom",
cbar_mode="edge",
cbar_pad=0.25,
cbar_size="15%",
direction="column"
)
Z, extent = get_demo_image()
cmaps = ["autumn", "summer"]
for i in range(4):
im = grid[i].imshow(Z, extent=extent, cmap=cmaps[i//2])
if i % 2:
grid.cbar_axes[i//2].colorbar(im)
for cax in grid.cbar_axes:
cax.axis[cax.orientation].set_label("Bar")
# This affects all Axes as share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
def demo_right_cbar(fig):
"""
A grid of 2x2 images. Each row has its own colorbar.
"""
grid = AxesGrid(fig, 122, # similar to subplot(122)
nrows_ncols=(2, 2),
axes_pad=0.10,
label_mode="1",
share_all=True,
cbar_location="right",
cbar_mode="edge",
cbar_size="7%",
cbar_pad="2%",
)
Z, extent = get_demo_image()
cmaps = ["spring", "winter"]
for i in range(4):
im = grid[i].imshow(Z, extent=extent, cmap=cmaps[i//2])
if i % 2:
grid.cbar_axes[i//2].colorbar(im)
for cax in grid.cbar_axes:
cax.axis[cax.orientation].set_label('Foo')
# This affects all Axes because we set share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
fig = plt.figure()
demo_bottom_cbar(fig)
demo_right_cbar(fig)
plt.show()
| stable__gallery__axes_grid1__demo_edge_colorbar | 0 | figure_000.png | Per-row or per-column colorbars — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_edge_colorbar.html#sphx-glr-download-gallery-axes-grid1-demo-edge-colorbar-py | https://matplotlib.org/stable/_downloads/c58f7f66a7206520d8eef2c5a8a20d72/demo_edge_colorbar.py | demo_edge_colorbar.py | axes_grid1 | ok | 1 | null | |
"""
===============================
Axes with a fixed physical size
===============================
Note that this can be accomplished with the main library for
Axes on Figures that do not change size: :ref:`fixed_size_axes`
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Divider, Size
# %%
fig = plt.figure(figsize=(6, 6))
# The first items are for padding and the second items are for the Axes.
# sizes are in inch.
h = [Size.Fixed(1.0), Size.Fixed(4.5)]
v = [Size.Fixed(0.7), Size.Fixed(5.)]
divider = Divider(fig, (0, 0, 1, 1), h, v, aspect=False)
# The width and height of the rectangle are ignored.
ax = fig.add_axes(divider.get_position(),
axes_locator=divider.new_locator(nx=1, ny=1))
ax.plot([1, 2, 3])
# %%
fig = plt.figure(figsize=(6, 6))
# The first & third items are for padding and the second items are for the
# Axes. Sizes are in inches.
h = [Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2)]
v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]
divider = Divider(fig, (0, 0, 1, 1), h, v, aspect=False)
# The width and height of the rectangle are ignored.
ax = fig.add_axes(divider.get_position(),
axes_locator=divider.new_locator(nx=1, ny=1))
ax.plot([1, 2, 3])
plt.show()
| stable__gallery__axes_grid1__demo_fixed_size_axes | 0 | figure_000.png | Axes with a fixed physical size — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_fixed_size_axes.html#sphx-glr-download-gallery-axes-grid1-demo-fixed-size-axes-py | https://matplotlib.org/stable/_downloads/88a68d33e6dc95f3756002ca22961251/demo_fixed_size_axes.py | demo_fixed_size_axes.py | axes_grid1 | ok | 2 | null | |
"""
===============================
Axes with a fixed physical size
===============================
Note that this can be accomplished with the main library for
Axes on Figures that do not change size: :ref:`fixed_size_axes`
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Divider, Size
# %%
fig = plt.figure(figsize=(6, 6))
# The first items are for padding and the second items are for the Axes.
# sizes are in inch.
h = [Size.Fixed(1.0), Size.Fixed(4.5)]
v = [Size.Fixed(0.7), Size.Fixed(5.)]
divider = Divider(fig, (0, 0, 1, 1), h, v, aspect=False)
# The width and height of the rectangle are ignored.
ax = fig.add_axes(divider.get_position(),
axes_locator=divider.new_locator(nx=1, ny=1))
ax.plot([1, 2, 3])
# %%
fig = plt.figure(figsize=(6, 6))
# The first & third items are for padding and the second items are for the
# Axes. Sizes are in inches.
h = [Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2)]
v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]
divider = Divider(fig, (0, 0, 1, 1), h, v, aspect=False)
# The width and height of the rectangle are ignored.
ax = fig.add_axes(divider.get_position(),
axes_locator=divider.new_locator(nx=1, ny=1))
ax.plot([1, 2, 3])
plt.show()
| stable__gallery__axes_grid1__demo_fixed_size_axes | 1 | figure_001.png | Axes with a fixed physical size — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_fixed_size_axes.html#sphx-glr-download-gallery-axes-grid1-demo-fixed-size-axes-py | https://matplotlib.org/stable/_downloads/88a68d33e6dc95f3756002ca22961251/demo_fixed_size_axes.py | demo_fixed_size_axes.py | axes_grid1 | ok | 2 | null | |
"""
=========================================
ImageGrid cells with a fixed aspect ratio
=========================================
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
fig = plt.figure()
grid1 = ImageGrid(fig, 121, (2, 2), axes_pad=0.1,
aspect=True, share_all=True)
for i in [0, 1]:
grid1[i].set_aspect(2)
grid2 = ImageGrid(fig, 122, (2, 2), axes_pad=0.1,
aspect=True, share_all=True)
for i in [1, 3]:
grid2[i].set_aspect(2)
plt.show()
| stable__gallery__axes_grid1__demo_imagegrid_aspect | 0 | figure_000.png | ImageGrid cells with a fixed aspect ratio — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/demo_imagegrid_aspect.html#sphx-glr-download-gallery-axes-grid1-demo-imagegrid-aspect-py | https://matplotlib.org/stable/_downloads/833e25177c1678266fcda4fb016bbcd7/demo_imagegrid_aspect.py | demo_imagegrid_aspect.py | axes_grid1 | ok | 1 | null | |
"""
==================
Inset locator demo
==================
"""
# %%
# The `.inset_locator`'s `~.inset_locator.inset_axes` allows
# easily placing insets in the corners of the Axes by specifying a width and
# height and optionally a location (loc) that accepts locations as codes,
# similar to `~matplotlib.axes.Axes.legend`.
# By default, the inset is offset by some points from the axes,
# controlled via the *borderpad* parameter.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, (ax, ax2) = plt.subplots(1, 2, figsize=[5.5, 2.8])
# Create inset of width 1.3 inches and height 0.9 inches
# at the default upper right location.
axins = inset_axes(ax, width=1.3, height=0.9)
# Create inset of width 30% and height 40% of the parent Axes' bounding box
# at the lower left corner.
axins2 = inset_axes(ax, width="30%", height="40%", loc="lower left")
# Create inset of mixed specifications in the second subplot;
# width is 30% of parent Axes' bounding box and
# height is 1 inch at the upper left corner.
axins3 = inset_axes(ax2, width="30%", height=1., loc="upper left")
# Create an inset in the lower right corner with borderpad=1, i.e.
# 10 points padding (as 10pt is the default fontsize) to the parent Axes.
axins4 = inset_axes(ax2, width="20%", height="20%", loc="lower right", borderpad=1)
# Turn ticklabels of insets off
for axi in [axins, axins2, axins3, axins4]:
axi.tick_params(labelleft=False, labelbottom=False)
plt.show()
# %%
# The parameters *bbox_to_anchor* and *bbox_transform* can be used for a more
# fine-grained control over the inset position and size or even to position
# the inset at completely arbitrary positions.
# The *bbox_to_anchor* sets the bounding box in coordinates according to the
# *bbox_transform*.
#
fig = plt.figure(figsize=[5.5, 2.8])
ax = fig.add_subplot(121)
# We use the Axes transform as bbox_transform. Therefore, the bounding box
# needs to be specified in axes coordinates ((0, 0) is the lower left corner
# of the Axes, (1, 1) is the upper right corner).
# The bounding box (.2, .4, .6, .5) starts at (.2, .4) and ranges to (.8, .9)
# in those coordinates.
# Inside this bounding box an inset of half the bounding box' width and
# three quarters of the bounding box' height is created. The lower left corner
# of the inset is aligned to the lower left corner of the bounding box.
# The inset is then offset by the default 0.5 in units of the font size.
axins = inset_axes(ax, width="50%", height="75%",
bbox_to_anchor=(.2, .4, .6, .5),
bbox_transform=ax.transAxes, loc="lower left")
# For visualization purposes we mark the bounding box by a rectangle
ax.add_patch(plt.Rectangle((.2, .4), .6, .5, ls="--", ec="c", fc="none",
transform=ax.transAxes))
# We set the axis limits to something other than the default, in order to not
# distract from the fact that axes coordinates are used here.
ax.set(xlim=(0, 10), ylim=(0, 10))
# Note how the two following insets are created at the same positions, one by
# use of the default parent Axes' bbox and the other via a bbox in Axes
# coordinates and the respective transform.
ax2 = fig.add_subplot(222)
axins2 = inset_axes(ax2, width="30%", height="50%")
ax3 = fig.add_subplot(224)
axins3 = inset_axes(ax3, width="100%", height="100%",
bbox_to_anchor=(.7, .5, .3, .5),
bbox_transform=ax3.transAxes)
# For visualization purposes we mark the bounding box by a rectangle
ax2.add_patch(plt.Rectangle((0, 0), 1, 1, ls="--", lw=2, ec="c", fc="none"))
ax3.add_patch(plt.Rectangle((.7, .5), .3, .5, ls="--", lw=2,
ec="c", fc="none"))
# Turn ticklabels off
for axi in [axins2, axins3, ax2, ax3]:
axi.tick_params(labelleft=False, labelbottom=False)
plt.show()
# %%
# In the above the Axes transform together with 4-tuple bounding boxes has been
# used as it mostly is useful to specify an inset relative to the Axes it is
# an inset to. However, other use cases are equally possible. The following
# example examines some of those.
#
fig = plt.figure(figsize=[5.5, 2.8])
ax = fig.add_subplot(131)
# Create an inset outside the Axes
axins = inset_axes(ax, width="100%", height="100%",
bbox_to_anchor=(1.05, .6, .5, .4),
bbox_transform=ax.transAxes, loc="upper left", borderpad=0)
axins.tick_params(left=False, right=True, labelleft=False, labelright=True)
# Create an inset with a 2-tuple bounding box. Note that this creates a
# bbox without extent. This hence only makes sense when specifying
# width and height in absolute units (inches).
axins2 = inset_axes(ax, width=0.5, height=0.4,
bbox_to_anchor=(0.33, 0.25),
bbox_transform=ax.transAxes, loc="lower left", borderpad=0)
ax2 = fig.add_subplot(133)
ax2.set_xscale("log")
ax2.set(xlim=(1e-6, 1e6), ylim=(-2, 6))
# Create inset in data coordinates using ax.transData as transform
axins3 = inset_axes(ax2, width="100%", height="100%",
bbox_to_anchor=(1e-2, 2, 1e3, 3),
bbox_transform=ax2.transData, loc="upper left", borderpad=0)
# Create an inset horizontally centered in figure coordinates and vertically
# bound to line up with the Axes.
from matplotlib.transforms import blended_transform_factory # noqa
transform = blended_transform_factory(fig.transFigure, ax2.transAxes)
axins4 = inset_axes(ax2, width="16%", height="34%",
bbox_to_anchor=(0, 0, 1, 1),
bbox_transform=transform, loc="lower center", borderpad=0)
plt.show()
| stable__gallery__axes_grid1__inset_locator_demo | 0 | figure_000.png | Inset locator demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/inset_locator_demo.html#sphx-glr-download-gallery-axes-grid1-inset-locator-demo-py | https://matplotlib.org/stable/_downloads/f8248729044d7fef8f20a43731251e38/inset_locator_demo.py | inset_locator_demo.py | axes_grid1 | ok | 3 | null | |
"""
====================
Inset locator demo 2
====================
This demo shows how to create a zoomed inset via `.zoomed_inset_axes`.
In the first subplot an `.AnchoredSizeBar` shows the zoom effect.
In the second subplot a connection to the region of interest is
created via `.mark_inset`.
A version of the second subplot, not using the toolkit, is available in
:doc:`/gallery/subplots_axes_and_figures/zoom_inset_axes`.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
from mpl_toolkits.axes_grid1.inset_locator import mark_inset, zoomed_inset_axes
fig, (ax, ax2) = plt.subplots(ncols=2, figsize=[6, 3])
# First subplot, showing an inset with a size bar.
ax.set_aspect(1)
axins = zoomed_inset_axes(ax, zoom=0.5, loc='upper right')
# fix the number of ticks on the inset Axes
axins.yaxis.get_major_locator().set_params(nbins=7)
axins.xaxis.get_major_locator().set_params(nbins=7)
axins.tick_params(labelleft=False, labelbottom=False)
def add_sizebar(ax, size):
asb = AnchoredSizeBar(ax.transData,
size,
str(size),
loc="lower center",
pad=0.1, borderpad=0.5, sep=5,
frameon=False)
ax.add_artist(asb)
add_sizebar(ax, 0.5)
add_sizebar(axins, 0.5)
# Second subplot, showing an image with an inset zoom and a marked inset
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy") # 15x15 array
extent = (-3, 4, -4, 3)
Z2 = np.zeros((150, 150))
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z
ax2.imshow(Z2, extent=extent, origin="lower")
axins2 = zoomed_inset_axes(ax2, zoom=6, loc="upper right")
axins2.imshow(Z2, extent=extent, origin="lower")
# subregion of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins2.set_xlim(x1, x2)
axins2.set_ylim(y1, y2)
# fix the number of ticks on the inset Axes
axins2.yaxis.get_major_locator().set_params(nbins=7)
axins2.xaxis.get_major_locator().set_params(nbins=7)
axins2.tick_params(labelleft=False, labelbottom=False)
# draw a bbox of the region of the inset Axes in the parent Axes and
# connecting lines between the bbox and the inset Axes area
mark_inset(ax2, axins2, loc1=2, loc2=4, fc="none", ec="0.5")
plt.show()
| stable__gallery__axes_grid1__inset_locator_demo2 | 0 | figure_000.png | Inset locator demo 2 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/inset_locator_demo2.html#sphx-glr-download-gallery-axes-grid1-inset-locator-demo2-py | https://matplotlib.org/stable/_downloads/ffced02a69365d873f495b7cd6725498/inset_locator_demo2.py | inset_locator_demo2.py | axes_grid1 | ok | 1 | null | |
"""
===============
Parasite Simple
===============
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
host = host_subplot(111)
par = host.twinx()
host.set_xlabel("Distance")
host.set_ylabel("Density")
par.set_ylabel("Temperature")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature")
host.legend(labelcolor="linecolor")
host.yaxis.label.set_color(p1.get_color())
par.yaxis.label.set_color(p2.get_color())
plt.show()
| stable__gallery__axes_grid1__parasite_simple | 0 | figure_000.png | Parasite Simple — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/parasite_simple.html#sphx-glr-download-gallery-axes-grid1-parasite-simple-py | https://matplotlib.org/stable/_downloads/88ad12e90a4c8c93f13b433c0f9c244f/parasite_simple.py | parasite_simple.py | axes_grid1 | ok | 1 | null | |
"""
================
Parasite Simple2
================
"""
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
from mpl_toolkits.axes_grid1.parasite_axes import HostAxes
obs = [["01_S1", 3.88, 0.14, 1970, 63],
["01_S4", 5.6, 0.82, 1622, 150],
["02_S1", 2.4, 0.54, 1570, 40],
["03_S1", 4.1, 0.62, 2380, 170]]
fig = plt.figure()
ax_kms = fig.add_subplot(axes_class=HostAxes, aspect=1)
# angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc
pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5
aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.)
ax_pm = ax_kms.twin(aux_trans)
for n, ds, dse, w, we in obs:
time = ((2007 + (10. + 4/30.)/12) - 1988.5)
v = ds / time * pm_to_kms
ve = dse / time * pm_to_kms
ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k")
ax_kms.axis["bottom"].set_label("Linear velocity at 2.3 kpc [km/s]")
ax_kms.axis["left"].set_label("FWHM [km/s]")
ax_pm.axis["top"].set_label(r"Proper Motion [$''$/yr]")
ax_pm.axis["top"].label.set_visible(True)
ax_pm.axis["right"].major_ticklabels.set_visible(False)
ax_kms.set_xlim(950, 3700)
ax_kms.set_ylim(950, 3100)
# xlim and ylim of ax_pms will be automatically adjusted.
plt.show()
| stable__gallery__axes_grid1__parasite_simple2 | 0 | figure_000.png | Parasite Simple2 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/parasite_simple2.html#sphx-glr-download-gallery-axes-grid1-parasite-simple2-py | https://matplotlib.org/stable/_downloads/7cde5ea64c654f0494cddafd39449630/parasite_simple2.py | parasite_simple2.py | axes_grid1 | ok | 1 | null | |
"""
====================================================
Align histogram to scatter plot using locatable Axes
====================================================
Show the marginal distributions of a scatter plot as histograms at the sides of
the plot.
For a nice alignment of the main Axes with the marginals, the Axes positions
are defined by a ``Divider``, produced via `.make_axes_locatable`. Note that
the ``Divider`` API allows setting Axes sizes and pads in inches, which is its
main feature.
If one wants to set Axes sizes and pads relative to the main Figure, see the
:doc:`/gallery/lines_bars_and_markers/scatter_hist` example.
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
fig, ax = plt.subplots(figsize=(5.5, 5.5))
# the scatter plot:
ax.scatter(x, y)
# Set aspect of the main Axes.
ax.set_aspect(1.)
# create new Axes on the right and on the top of the current Axes
divider = make_axes_locatable(ax)
# below height and pad are in inches
ax_histx = divider.append_axes("top", 1.2, pad=0.1, sharex=ax)
ax_histy = divider.append_axes("right", 1.2, pad=0.1, sharey=ax)
# make some labels invisible
ax_histx.xaxis.set_tick_params(labelbottom=False)
ax_histy.yaxis.set_tick_params(labelleft=False)
# now determine nice limits by hand:
binwidth = 0.25
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
lim = (int(xymax/binwidth) + 1)*binwidth
bins = np.arange(-lim, lim + binwidth, binwidth)
ax_histx.hist(x, bins=bins)
ax_histy.hist(y, bins=bins, orientation='horizontal')
# the xaxis of ax_histx and yaxis of ax_histy are shared with ax,
# thus there is no need to manually adjust the xlim and ylim of these
# axis.
ax_histx.set_yticks([0, 50, 100])
ax_histy.set_xticks([0, 50, 100])
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `mpl_toolkits.axes_grid1.axes_divider.make_axes_locatable`
# - `matplotlib.axes.Axes.set_aspect`
# - `matplotlib.axes.Axes.scatter`
# - `matplotlib.axes.Axes.hist`
| stable__gallery__axes_grid1__scatter_hist_locatable_axes | 0 | figure_000.png | Align histogram to scatter plot using locatable Axes — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/scatter_hist_locatable_axes.html#sphx-glr-download-gallery-axes-grid1-scatter-hist-locatable-axes-py | https://matplotlib.org/stable/_downloads/51e912a5cf217f8c6647ebf9f5539d38/scatter_hist_locatable_axes.py | scatter_hist_locatable_axes.py | axes_grid1 | ok | 1 | null | |
"""
=======================
Simple Anchored Artists
=======================
This example illustrates the use of the anchored helper classes found in
:mod:`matplotlib.offsetbox` and in :mod:`mpl_toolkits.axes_grid1`.
An implementation of a similar figure, but without use of the toolkit,
can be found in :doc:`/gallery/misc/anchored_artists`.
"""
import matplotlib.pyplot as plt
def draw_text(ax):
"""
Draw two text-boxes, anchored by different corners to the upper-left
corner of the figure.
"""
from matplotlib.offsetbox import AnchoredText
at = AnchoredText("Figure 1a",
loc='upper left', prop=dict(size=8), frameon=True,
)
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at)
at2 = AnchoredText("Figure 1(b)",
loc='lower left', prop=dict(size=8), frameon=True,
bbox_to_anchor=(0., 1.),
bbox_transform=ax.transAxes
)
at2.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at2)
def draw_circle(ax):
"""
Draw a circle in axis coordinates
"""
from matplotlib.patches import Circle
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea
ada = AnchoredDrawingArea(20, 20, 0, 0,
loc='upper right', pad=0., frameon=False)
p = Circle((10, 10), 10)
ada.da.add_artist(p)
ax.add_artist(ada)
def draw_sizebar(ax):
"""
Draw a horizontal bar with length of 0.1 in data coordinates,
with a fixed label underneath.
"""
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
asb = AnchoredSizeBar(ax.transData,
0.1,
r"1$^{\prime}$",
loc='lower center',
pad=0.1, borderpad=0.5, sep=5,
frameon=False)
ax.add_artist(asb)
fig, ax = plt.subplots()
ax.set_aspect(1.)
draw_text(ax)
draw_circle(ax)
draw_sizebar(ax)
plt.show()
| stable__gallery__axes_grid1__simple_anchored_artists | 0 | figure_000.png | Simple Anchored Artists — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/simple_anchored_artists.html#sphx-glr-download-gallery-axes-grid1-simple-anchored-artists-py | https://matplotlib.org/stable/_downloads/7aa510be32a5c72df8a01d67a5890deb/simple_anchored_artists.py | simple_anchored_artists.py | axes_grid1 | ok | 1 | null | |
"""
=====================
Simple Axes Divider 1
=====================
See also :ref:`axes_grid`.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Divider, Size
def label_axes(ax, text):
"""Place a label at the center of an Axes, and remove the axis ticks."""
ax.text(.5, .5, text, transform=ax.transAxes,
horizontalalignment="center", verticalalignment="center")
ax.tick_params(bottom=False, labelbottom=False,
left=False, labelleft=False)
# %%
# Fixed Axes sizes; fixed paddings.
fig = plt.figure(figsize=(6, 6))
fig.suptitle("Fixed axes sizes, fixed paddings")
# Sizes are in inches.
horiz = [Size.Fixed(1.), Size.Fixed(.5), Size.Fixed(1.5), Size.Fixed(.5)]
vert = [Size.Fixed(1.5), Size.Fixed(.5), Size.Fixed(1.)]
rect = (0.1, 0.1, 0.8, 0.8)
# Divide the Axes rectangle into a grid with sizes specified by horiz * vert.
div = Divider(fig, rect, horiz, vert, aspect=False)
# The rect parameter will actually be ignored and overridden by axes_locator.
ax1 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=0))
label_axes(ax1, "nx=0, ny=0")
ax2 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=2))
label_axes(ax2, "nx=0, ny=2")
ax3 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, ny=2))
label_axes(ax3, "nx=2, ny=2")
ax4 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, nx1=4, ny=0))
label_axes(ax4, "nx=2, nx1=4, ny=0")
# %%
# Axes sizes that scale with the figure size; fixed paddings.
fig = plt.figure(figsize=(6, 6))
fig.suptitle("Scalable axes sizes, fixed paddings")
horiz = [Size.Scaled(1.5), Size.Fixed(.5), Size.Scaled(1.), Size.Scaled(.5)]
vert = [Size.Scaled(1.), Size.Fixed(.5), Size.Scaled(1.5)]
rect = (0.1, 0.1, 0.8, 0.8)
# Divide the Axes rectangle into a grid with sizes specified by horiz * vert.
div = Divider(fig, rect, horiz, vert, aspect=False)
# The rect parameter will actually be ignored and overridden by axes_locator.
ax1 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=0))
label_axes(ax1, "nx=0, ny=0")
ax2 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=2))
label_axes(ax2, "nx=0, ny=2")
ax3 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, ny=2))
label_axes(ax3, "nx=2, ny=2")
ax4 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, nx1=4, ny=0))
label_axes(ax4, "nx=2, nx1=4, ny=0")
plt.show()
| stable__gallery__axes_grid1__simple_axes_divider1 | 0 | figure_000.png | Simple Axes Divider 1 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/simple_axes_divider1.html#sphx-glr-download-gallery-axes-grid1-simple-axes-divider1-py | https://matplotlib.org/stable/_downloads/43ee01b4b62cb46e1521f86c6de1a0a4/simple_axes_divider1.py | simple_axes_divider1.py | axes_grid1 | ok | 2 | null | |
"""
=====================
Simple Axes Divider 1
=====================
See also :ref:`axes_grid`.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Divider, Size
def label_axes(ax, text):
"""Place a label at the center of an Axes, and remove the axis ticks."""
ax.text(.5, .5, text, transform=ax.transAxes,
horizontalalignment="center", verticalalignment="center")
ax.tick_params(bottom=False, labelbottom=False,
left=False, labelleft=False)
# %%
# Fixed Axes sizes; fixed paddings.
fig = plt.figure(figsize=(6, 6))
fig.suptitle("Fixed axes sizes, fixed paddings")
# Sizes are in inches.
horiz = [Size.Fixed(1.), Size.Fixed(.5), Size.Fixed(1.5), Size.Fixed(.5)]
vert = [Size.Fixed(1.5), Size.Fixed(.5), Size.Fixed(1.)]
rect = (0.1, 0.1, 0.8, 0.8)
# Divide the Axes rectangle into a grid with sizes specified by horiz * vert.
div = Divider(fig, rect, horiz, vert, aspect=False)
# The rect parameter will actually be ignored and overridden by axes_locator.
ax1 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=0))
label_axes(ax1, "nx=0, ny=0")
ax2 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=2))
label_axes(ax2, "nx=0, ny=2")
ax3 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, ny=2))
label_axes(ax3, "nx=2, ny=2")
ax4 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, nx1=4, ny=0))
label_axes(ax4, "nx=2, nx1=4, ny=0")
# %%
# Axes sizes that scale with the figure size; fixed paddings.
fig = plt.figure(figsize=(6, 6))
fig.suptitle("Scalable axes sizes, fixed paddings")
horiz = [Size.Scaled(1.5), Size.Fixed(.5), Size.Scaled(1.), Size.Scaled(.5)]
vert = [Size.Scaled(1.), Size.Fixed(.5), Size.Scaled(1.5)]
rect = (0.1, 0.1, 0.8, 0.8)
# Divide the Axes rectangle into a grid with sizes specified by horiz * vert.
div = Divider(fig, rect, horiz, vert, aspect=False)
# The rect parameter will actually be ignored and overridden by axes_locator.
ax1 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=0))
label_axes(ax1, "nx=0, ny=0")
ax2 = fig.add_axes(rect, axes_locator=div.new_locator(nx=0, ny=2))
label_axes(ax2, "nx=0, ny=2")
ax3 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, ny=2))
label_axes(ax3, "nx=2, ny=2")
ax4 = fig.add_axes(rect, axes_locator=div.new_locator(nx=2, nx1=4, ny=0))
label_axes(ax4, "nx=2, nx1=4, ny=0")
plt.show()
| stable__gallery__axes_grid1__simple_axes_divider1 | 1 | figure_001.png | Simple Axes Divider 1 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/simple_axes_divider1.html#sphx-glr-download-gallery-axes-grid1-simple-axes-divider1-py | https://matplotlib.org/stable/_downloads/43ee01b4b62cb46e1521f86c6de1a0a4/simple_axes_divider1.py | simple_axes_divider1.py | axes_grid1 | ok | 2 | null | |
"""
=====================
Simple axes divider 3
=====================
See also :ref:`axes_grid`.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Divider
import mpl_toolkits.axes_grid1.axes_size as Size
fig = plt.figure(figsize=(5.5, 4))
# the rect parameter will be ignored as we will set axes_locator
rect = (0.1, 0.1, 0.8, 0.8)
ax = [fig.add_axes(rect, label="%d" % i) for i in range(4)]
horiz = [Size.AxesX(ax[0]), Size.Fixed(.5), Size.AxesX(ax[1])]
vert = [Size.AxesY(ax[0]), Size.Fixed(.5), Size.AxesY(ax[2])]
# divide the Axes rectangle into grid whose size is specified by horiz * vert
divider = Divider(fig, rect, horiz, vert, aspect=False)
ax[0].set_axes_locator(divider.new_locator(nx=0, ny=0))
ax[1].set_axes_locator(divider.new_locator(nx=2, ny=0))
ax[2].set_axes_locator(divider.new_locator(nx=0, ny=2))
ax[3].set_axes_locator(divider.new_locator(nx=2, ny=2))
ax[0].set_xlim(0, 2)
ax[1].set_xlim(0, 1)
ax[0].set_ylim(0, 1)
ax[2].set_ylim(0, 2)
divider.set_aspect(1.)
for ax1 in ax:
ax1.tick_params(labelbottom=False, labelleft=False)
plt.show()
| stable__gallery__axes_grid1__simple_axes_divider3 | 0 | figure_000.png | Simple axes divider 3 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/simple_axes_divider3.html#sphx-glr-download-gallery-axes-grid1-simple-axes-divider3-py | https://matplotlib.org/stable/_downloads/bb0580289006b321b47cf070fd5c1bfb/simple_axes_divider3.py | simple_axes_divider3.py | axes_grid1 | ok | 1 | null | |
"""
================
Simple ImageGrid
================
Align multiple images using `~mpl_toolkits.axes_grid1.axes_grid.ImageGrid`.
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import ImageGrid
im1 = np.arange(100).reshape((10, 10))
im2 = im1.T
im3 = np.flipud(im1)
im4 = np.fliplr(im2)
fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(2, 2), # creates 2x2 grid of Axes
axes_pad=0.1, # pad between Axes in inch.
)
for ax, im in zip(grid, [im1, im2, im3, im4]):
# Iterating over the grid returns the Axes.
ax.imshow(im)
plt.show()
| stable__gallery__axes_grid1__simple_axesgrid | 0 | figure_000.png | Simple ImageGrid — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/simple_axesgrid.html#sphx-glr-download-gallery-axes-grid1-simple-axesgrid-py | https://matplotlib.org/stable/_downloads/c28e31130cca60f0a4ac710f3fbf96c8/simple_axesgrid.py | simple_axesgrid.py | axes_grid1 | ok | 1 | null | |
"""
==================
Simple ImageGrid 2
==================
Align multiple images of different sizes using
`~mpl_toolkits.axes_grid1.axes_grid.ImageGrid`.
"""
import matplotlib.pyplot as plt
from matplotlib import cbook
from mpl_toolkits.axes_grid1 import ImageGrid
fig = plt.figure(figsize=(5.5, 3.5))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(1, 3),
axes_pad=0.1,
label_mode="L",
)
# demo image
Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy")
im1 = Z
im2 = Z[:, :10]
im3 = Z[:, 10:]
vmin, vmax = Z.min(), Z.max()
for ax, im in zip(grid, [im1, im2, im3]):
ax.imshow(im, origin="lower", vmin=vmin, vmax=vmax)
plt.show()
| stable__gallery__axes_grid1__simple_axesgrid2 | 0 | figure_000.png | Simple ImageGrid 2 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/simple_axesgrid2.html#sphx-glr-download-gallery-axes-grid1-simple-axesgrid2-py | https://matplotlib.org/stable/_downloads/a6da60ccaa4eeba18fd39bf89cef94aa/simple_axesgrid2.py | simple_axesgrid2.py | axes_grid1 | ok | 1 | null | |
"""
================
Simple Axisline4
================
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import host_subplot
ax = host_subplot(111)
xx = np.arange(0, 2*np.pi, 0.01)
ax.plot(xx, np.sin(xx))
ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis
ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi],
labels=["$0$", r"$\frac{1}{2}\pi$",
r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])
ax2.axis["right"].major_ticklabels.set_visible(False)
ax2.axis["top"].major_ticklabels.set_visible(True)
plt.show()
| stable__gallery__axes_grid1__simple_axisline4 | 0 | figure_000.png | Simple Axisline4 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axes_grid1/simple_axisline4.html#sphx-glr-download-gallery-axes-grid1-simple-axisline4-py | https://matplotlib.org/stable/_downloads/416437b16432ec060b1f3910fdfe5d78/simple_axisline4.py | simple_axisline4.py | axes_grid1 | ok | 1 | null | |
"""
==============
Axis Direction
==============
"""
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
def setup_axes(fig, pos):
ax = fig.add_subplot(pos, axes_class=axisartist.Axes)
ax.set_ylim(-0.1, 1.5)
ax.set_yticks([0, 1])
ax.axis[:].set_visible(False)
ax.axis["x"] = ax.new_floating_axis(1, 0.5)
ax.axis["x"].set_axisline_style("->", size=1.5)
return ax
plt.rcParams.update({
"axes.titlesize": "medium",
"axes.titley": 1.1,
})
fig = plt.figure(figsize=(10, 4))
fig.subplots_adjust(bottom=0.1, top=0.9, left=0.05, right=0.95)
ax1 = setup_axes(fig, 251)
ax1.axis["x"].set_axis_direction("left")
ax2 = setup_axes(fig, 252)
ax2.axis["x"].label.set_text("Label")
ax2.axis["x"].toggle(ticklabels=False)
ax2.axis["x"].set_axislabel_direction("+")
ax2.set_title("label direction=$+$")
ax3 = setup_axes(fig, 253)
ax3.axis["x"].label.set_text("Label")
ax3.axis["x"].toggle(ticklabels=False)
ax3.axis["x"].set_axislabel_direction("-")
ax3.set_title("label direction=$-$")
ax4 = setup_axes(fig, 254)
ax4.axis["x"].set_ticklabel_direction("+")
ax4.set_title("ticklabel direction=$+$")
ax5 = setup_axes(fig, 255)
ax5.axis["x"].set_ticklabel_direction("-")
ax5.set_title("ticklabel direction=$-$")
ax7 = setup_axes(fig, 257)
ax7.axis["x"].label.set_text("rotation=10")
ax7.axis["x"].label.set_rotation(10)
ax7.axis["x"].toggle(ticklabels=False)
ax8 = setup_axes(fig, 258)
ax8.axis["x"].set_axislabel_direction("-")
ax8.axis["x"].label.set_text("rotation=10")
ax8.axis["x"].label.set_rotation(10)
ax8.axis["x"].toggle(ticklabels=False)
plt.show()
| stable__gallery__axisartist__axis_direction | 0 | figure_000.png | Axis Direction — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/axis_direction.html#sphx-glr-download-gallery-axisartist-axis-direction-py | https://matplotlib.org/stable/_downloads/3d8125065415e7722e62573de9ae1073/axis_direction.py | axis_direction.py | axisartist | ok | 1 | null | |
"""
===================
axis_direction demo
===================
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist as axisartist
import mpl_toolkits.axisartist.angle_helper as angle_helper
import mpl_toolkits.axisartist.grid_finder as grid_finder
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
GridHelperCurveLinear
def setup_axes(fig, rect):
"""Polar projection, but in a rectangular box."""
# see demo_curvelinear_grid.py for details
grid_helper = GridHelperCurveLinear(
(
Affine2D().scale(np.pi/180., 1.) +
PolarAxes.PolarTransform(apply_theta_transforms=False)
),
extreme_finder=angle_helper.ExtremeFinderCycle(
20, 20,
lon_cycle=360, lat_cycle=None,
lon_minmax=None, lat_minmax=(0, np.inf),
),
grid_locator1=angle_helper.LocatorDMS(12),
grid_locator2=grid_finder.MaxNLocator(5),
tick_formatter1=angle_helper.FormatterDMS(),
)
ax = fig.add_subplot(
rect, axes_class=axisartist.Axes, grid_helper=grid_helper,
aspect=1, xlim=(-5, 12), ylim=(-5, 10))
ax.axis[:].toggle(ticklabels=False)
ax.grid(color=".9")
return ax
def add_floating_axis1(ax):
ax.axis["lat"] = axis = ax.new_floating_axis(0, 30)
axis.label.set_text(r"$\theta = 30^{\circ}$")
axis.label.set_visible(True)
return axis
def add_floating_axis2(ax):
ax.axis["lon"] = axis = ax.new_floating_axis(1, 6)
axis.label.set_text(r"$r = 6$")
axis.label.set_visible(True)
return axis
fig = plt.figure(figsize=(8, 4), layout="constrained")
for i, d in enumerate(["bottom", "left", "top", "right"]):
ax = setup_axes(fig, rect=241+i)
axis = add_floating_axis1(ax)
axis.set_axis_direction(d)
ax.set(title=d)
for i, d in enumerate(["bottom", "left", "top", "right"]):
ax = setup_axes(fig, rect=245+i)
axis = add_floating_axis2(ax)
axis.set_axis_direction(d)
ax.set(title=d)
plt.show()
| stable__gallery__axisartist__demo_axis_direction | 0 | figure_000.png | axis_direction demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_axis_direction.html#sphx-glr-download-gallery-axisartist-demo-axis-direction-py | https://matplotlib.org/stable/_downloads/a209d398996b5e5fa1542119df3c251c/demo_axis_direction.py | demo_axis_direction.py | axisartist | ok | 1 | null | |
"""
================
Axis line styles
================
This example shows some configurations for axis style.
Note: The `mpl_toolkits.axisartist` Axes classes may be confusing for new
users. If the only aim is to obtain arrow heads at the ends of the axes,
rather check out the :doc:`/gallery/spines/centered_spines_with_arrows`
example.
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axisartist.axislines import AxesZero
fig = plt.figure()
ax = fig.add_subplot(axes_class=AxesZero)
for direction in ["xzero", "yzero"]:
# adds arrows at the ends of each axis
ax.axis[direction].set_axisline_style("-|>")
# adds X and Y-axis from the origin
ax.axis[direction].set_visible(True)
for direction in ["left", "right", "bottom", "top"]:
# hides borders
ax.axis[direction].set_visible(False)
x = np.linspace(-0.5, 1., 100)
ax.plot(x, np.sin(x*np.pi))
plt.show()
| stable__gallery__axisartist__demo_axisline_style | 0 | figure_000.png | Axis line styles — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_axisline_style.html#sphx-glr-download-gallery-axisartist-demo-axisline-style-py | https://matplotlib.org/stable/_downloads/2efbf158321b6ee9b59fa6e4e5367de6/demo_axisline_style.py | demo_axisline_style.py | axisartist | ok | 1 | null | |
"""
=====================
Curvilinear grid demo
=====================
Custom grid and ticklines.
This example demonstrates how to use
`~.grid_helper_curvelinear.GridHelperCurveLinear` to define custom grids and
ticklines by applying a transformation on the grid. This can be used, as
shown on the second plot, to create polar projections in a rectangular box.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import Axes, HostAxes, angle_helper
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
GridHelperCurveLinear
def curvelinear_test1(fig):
"""
Grid for custom transform.
"""
def tr(x, y): return x, y - x
def inv_tr(x, y): return x, y + x
grid_helper = GridHelperCurveLinear((tr, inv_tr))
ax1 = fig.add_subplot(1, 2, 1, axes_class=Axes, grid_helper=grid_helper)
# ax1 will have ticks and gridlines defined by the given transform (+
# transData of the Axes). Note that the transform of the Axes itself
# (i.e., transData) is not affected by the given transform.
xx, yy = tr(np.array([3, 6]), np.array([5, 10]))
ax1.plot(xx, yy)
ax1.set_aspect(1)
ax1.set_xlim(0, 10)
ax1.set_ylim(0, 10)
ax1.axis["t"] = ax1.new_floating_axis(0, 3)
ax1.axis["t2"] = ax1.new_floating_axis(1, 7)
ax1.grid(True, zorder=0)
def curvelinear_test2(fig):
"""
Polar projection, but in a rectangular box.
"""
# PolarAxes.PolarTransform takes radian. However, we want our coordinate
# system in degree
tr = Affine2D().scale(np.pi/180, 1) + PolarAxes.PolarTransform(
apply_theta_transforms=False)
# Polar projection, which involves cycle, and also has limits in
# its coordinates, needs a special method to find the extremes
# (min, max of the coordinate within the view).
extreme_finder = angle_helper.ExtremeFinderCycle(
nx=20, ny=20, # Number of sampling points in each direction.
lon_cycle=360, lat_cycle=None,
lon_minmax=None, lat_minmax=(0, np.inf),
)
# Find grid values appropriate for the coordinate (degree, minute, second).
grid_locator1 = angle_helper.LocatorDMS(12)
# Use an appropriate formatter. Note that the acceptable Locator and
# Formatter classes are a bit different than that of Matplotlib, which
# cannot directly be used here (this may be possible in the future).
tick_formatter1 = angle_helper.FormatterDMS()
grid_helper = GridHelperCurveLinear(
tr, extreme_finder=extreme_finder,
grid_locator1=grid_locator1, tick_formatter1=tick_formatter1)
ax1 = fig.add_subplot(
1, 2, 2, axes_class=HostAxes, grid_helper=grid_helper)
# make ticklabels of right and top axis visible.
ax1.axis["right"].major_ticklabels.set_visible(True)
ax1.axis["top"].major_ticklabels.set_visible(True)
# let right axis shows ticklabels for 1st coordinate (angle)
ax1.axis["right"].get_helper().nth_coord_ticks = 0
# let bottom axis shows ticklabels for 2nd coordinate (radius)
ax1.axis["bottom"].get_helper().nth_coord_ticks = 1
ax1.set_aspect(1)
ax1.set_xlim(-5, 12)
ax1.set_ylim(-5, 10)
ax1.grid(True, zorder=0)
# A parasite Axes with given transform
ax2 = ax1.get_aux_axes(tr)
# note that ax2.transData == tr + ax1.transData
# Anything you draw in ax2 will match the ticks and grids of ax1.
ax2.plot(np.linspace(0, 30, 51), np.linspace(10, 10, 51), linewidth=2)
ax2.pcolor(np.linspace(0, 90, 4), np.linspace(0, 10, 4),
np.arange(9).reshape((3, 3)))
ax2.contour(np.linspace(0, 90, 4), np.linspace(0, 10, 4),
np.arange(16).reshape((4, 4)), colors="k")
if __name__ == "__main__":
fig = plt.figure(figsize=(7, 4))
curvelinear_test1(fig)
curvelinear_test2(fig)
plt.show()
| stable__gallery__axisartist__demo_curvelinear_grid | 0 | figure_000.png | Curvilinear grid demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_curvelinear_grid.html#sphx-glr-download-gallery-axisartist-demo-curvelinear-grid-py | https://matplotlib.org/stable/_downloads/0dff3dd67468123eb00b27dd85176840/demo_curvelinear_grid.py | demo_curvelinear_grid.py | axisartist | ok | 1 | null | |
"""
======================
Demo CurveLinear Grid2
======================
Custom grid and ticklines.
This example demonstrates how to use GridHelperCurveLinear to define
custom grids and ticklines by applying a transformation on the grid.
As showcase on the plot, a 5x5 matrix is displayed on the Axes.
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axisartist.axislines import Axes
from mpl_toolkits.axisartist.grid_finder import (ExtremeFinderSimple,
MaxNLocator)
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
GridHelperCurveLinear
def curvelinear_test1(fig):
"""Grid for custom transform."""
def tr(x, y):
return np.sign(x)*abs(x)**.5, y
def inv_tr(x, y):
return np.sign(x)*x**2, y
grid_helper = GridHelperCurveLinear(
(tr, inv_tr),
extreme_finder=ExtremeFinderSimple(20, 20),
# better tick density
grid_locator1=MaxNLocator(nbins=6), grid_locator2=MaxNLocator(nbins=6))
ax1 = fig.add_subplot(axes_class=Axes, grid_helper=grid_helper)
# ax1 will have a ticks and gridlines defined by the given
# transform (+ transData of the Axes). Note that the transform of the Axes
# itself (i.e., transData) is not affected by the given transform.
ax1.imshow(np.arange(25).reshape(5, 5),
vmax=50, cmap=plt.cm.gray_r, origin="lower")
if __name__ == "__main__":
fig = plt.figure(figsize=(7, 4))
curvelinear_test1(fig)
plt.show()
| stable__gallery__axisartist__demo_curvelinear_grid2 | 0 | figure_000.png | Demo CurveLinear Grid2 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_curvelinear_grid2.html#sphx-glr-download-gallery-axisartist-demo-curvelinear-grid2-py | https://matplotlib.org/stable/_downloads/0466e9045f8fe3100f98c2a3b536994c/demo_curvelinear_grid2.py | demo_curvelinear_grid2.py | axisartist | ok | 1 | null | |
"""
==========================
``floating_axes`` features
==========================
Demonstration of features of the :mod:`.floating_axes` module:
* Using `~.axes.Axes.scatter` and `~.axes.Axes.bar` with changing the shape of
the plot.
* Using `~.floating_axes.GridHelperCurveLinear` to rotate the plot and set the
plot boundary.
* Using `~.Figure.add_subplot` to create a subplot using the return value from
`~.floating_axes.GridHelperCurveLinear`.
* Making a sector plot by adding more features to
`~.floating_axes.GridHelperCurveLinear`.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist.angle_helper as angle_helper
import mpl_toolkits.axisartist.floating_axes as floating_axes
from mpl_toolkits.axisartist.grid_finder import (DictFormatter, FixedLocator,
MaxNLocator)
# Fixing random state for reproducibility
np.random.seed(19680801)
def setup_axes1(fig, rect):
"""
A simple one.
"""
tr = Affine2D().scale(2, 1).rotate_deg(30)
grid_helper = floating_axes.GridHelperCurveLinear(
tr, extremes=(-0.5, 3.5, 0, 4),
grid_locator1=MaxNLocator(nbins=4),
grid_locator2=MaxNLocator(nbins=4))
ax1 = fig.add_subplot(
rect, axes_class=floating_axes.FloatingAxes, grid_helper=grid_helper)
ax1.grid()
aux_ax = ax1.get_aux_axes(tr)
return ax1, aux_ax
def setup_axes2(fig, rect):
"""
With custom locator and formatter.
Note that the extreme values are swapped.
"""
tr = PolarAxes.PolarTransform(apply_theta_transforms=False)
pi = np.pi
angle_ticks = [(0, r"$0$"),
(.25*pi, r"$\frac{1}{4}\pi$"),
(.5*pi, r"$\frac{1}{2}\pi$")]
grid_locator1 = FixedLocator([v for v, s in angle_ticks])
tick_formatter1 = DictFormatter(dict(angle_ticks))
grid_locator2 = MaxNLocator(2)
grid_helper = floating_axes.GridHelperCurveLinear(
tr, extremes=(.5*pi, 0, 2, 1),
grid_locator1=grid_locator1,
grid_locator2=grid_locator2,
tick_formatter1=tick_formatter1,
tick_formatter2=None)
ax1 = fig.add_subplot(
rect, axes_class=floating_axes.FloatingAxes, grid_helper=grid_helper)
ax1.grid()
# create a parasite Axes whose transData in RA, cz
aux_ax = ax1.get_aux_axes(tr)
aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
ax1.patch.zorder = 0.9 # but this has a side effect that the patch is
# drawn twice, and possibly over some other
# artists. So, we decrease the zorder a bit to
# prevent this.
return ax1, aux_ax
def setup_axes3(fig, rect):
"""
Sometimes, things like axis_direction need to be adjusted.
"""
# rotate a bit for better orientation
tr_rotate = Affine2D().translate(-95, 0)
# scale degree to radians
tr_scale = Affine2D().scale(np.pi/180., 1.)
tr = tr_rotate + tr_scale + PolarAxes.PolarTransform(
apply_theta_transforms=False)
grid_locator1 = angle_helper.LocatorHMS(4)
tick_formatter1 = angle_helper.FormatterHMS()
grid_locator2 = MaxNLocator(3)
# Specify theta limits in degrees
ra0, ra1 = 8.*15, 14.*15
# Specify radial limits
cz0, cz1 = 0, 14000
grid_helper = floating_axes.GridHelperCurveLinear(
tr, extremes=(ra0, ra1, cz0, cz1),
grid_locator1=grid_locator1,
grid_locator2=grid_locator2,
tick_formatter1=tick_formatter1,
tick_formatter2=None)
ax1 = fig.add_subplot(
rect, axes_class=floating_axes.FloatingAxes, grid_helper=grid_helper)
# adjust axis
ax1.axis["left"].set_axis_direction("bottom")
ax1.axis["right"].set_axis_direction("top")
ax1.axis["bottom"].set_visible(False)
ax1.axis["top"].set_axis_direction("bottom")
ax1.axis["top"].toggle(ticklabels=True, label=True)
ax1.axis["top"].major_ticklabels.set_axis_direction("top")
ax1.axis["top"].label.set_axis_direction("top")
ax1.axis["left"].label.set_text(r"cz [km$^{-1}$]")
ax1.axis["top"].label.set_text(r"$\alpha_{1950}$")
ax1.grid()
# create a parasite Axes whose transData in RA, cz
aux_ax = ax1.get_aux_axes(tr)
aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
ax1.patch.zorder = 0.9 # but this has a side effect that the patch is
# drawn twice, and possibly over some other
# artists. So, we decrease the zorder a bit to
# prevent this.
return ax1, aux_ax
# %%
fig = plt.figure(figsize=(8, 4))
fig.subplots_adjust(wspace=0.3, left=0.05, right=0.95)
ax1, aux_ax1 = setup_axes1(fig, 131)
aux_ax1.bar([0, 1, 2, 3], [3, 2, 1, 3])
ax2, aux_ax2 = setup_axes2(fig, 132)
theta = np.random.rand(10)*.5*np.pi
radius = np.random.rand(10) + 1.
aux_ax2.scatter(theta, radius)
ax3, aux_ax3 = setup_axes3(fig, 133)
theta = (8 + np.random.rand(10)*(14 - 8))*15. # in degrees
radius = np.random.rand(10)*14000.
aux_ax3.scatter(theta, radius)
plt.show()
| stable__gallery__axisartist__demo_floating_axes | 0 | figure_000.png | floating_axes features — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_floating_axes.html#sphx-glr-download-gallery-axisartist-demo-floating-axes-py | https://matplotlib.org/stable/_downloads/c53046419d84d1eb912e1ce17dcc1789/demo_floating_axes.py | demo_floating_axes.py | axisartist | ok | 1 | null | |
"""
==================
floating_axis demo
==================
Axis within rectangular frame.
The following code demonstrates how to put a floating polar curve within a
rectangular box. In order to get a better sense of polar curves, please look at
:doc:`/gallery/axisartist/demo_curvelinear_grid`.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import GridHelperCurveLinear, HostAxes
import mpl_toolkits.axisartist.angle_helper as angle_helper
def curvelinear_test2(fig):
"""Polar projection, but in a rectangular box."""
# see demo_curvelinear_grid.py for details
tr = Affine2D().scale(np.pi / 180., 1.) + PolarAxes.PolarTransform(
apply_theta_transforms=False)
extreme_finder = angle_helper.ExtremeFinderCycle(20,
20,
lon_cycle=360,
lat_cycle=None,
lon_minmax=None,
lat_minmax=(0, np.inf),
)
grid_locator1 = angle_helper.LocatorDMS(12)
tick_formatter1 = angle_helper.FormatterDMS()
grid_helper = GridHelperCurveLinear(tr,
extreme_finder=extreme_finder,
grid_locator1=grid_locator1,
tick_formatter1=tick_formatter1
)
ax1 = fig.add_subplot(axes_class=HostAxes, grid_helper=grid_helper)
# Now creates floating axis
# floating axis whose first coordinate (theta) is fixed at 60
ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 60)
axis.label.set_text(r"$\theta = 60^{\circ}$")
axis.label.set_visible(True)
# floating axis whose second coordinate (r) is fixed at 6
ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6)
axis.label.set_text(r"$r = 6$")
ax1.set_aspect(1.)
ax1.set_xlim(-5, 12)
ax1.set_ylim(-5, 10)
ax1.grid(True)
fig = plt.figure(figsize=(5, 5))
curvelinear_test2(fig)
plt.show()
| stable__gallery__axisartist__demo_floating_axis | 0 | figure_000.png | floating_axis demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_floating_axis.html#sphx-glr-download-gallery-axisartist-demo-floating-axis-py | https://matplotlib.org/stable/_downloads/12927e05bde893cbae7f16aaed1b87eb/demo_floating_axis.py | demo_floating_axis.py | axisartist | ok | 1 | null | |
"""
==================
Parasite Axes demo
==================
Create a parasite Axes. Such Axes would share the x scale with a host Axes,
but show a different scale in y direction.
This approach uses `mpl_toolkits.axes_grid1.parasite_axes.HostAxes` and
`mpl_toolkits.axes_grid1.parasite_axes.ParasiteAxes`.
The standard and recommended approach is to use instead standard Matplotlib
axes, as shown in the :doc:`/gallery/spines/multiple_yaxis_with_spines`
example.
An alternative approach using `mpl_toolkits.axes_grid1` and
`mpl_toolkits.axisartist` is shown in the
:doc:`/gallery/axisartist/demo_parasite_axes2` example.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axisartist.parasite_axes import HostAxes
fig = plt.figure()
host = fig.add_axes([0.15, 0.1, 0.65, 0.8], axes_class=HostAxes)
par1 = host.get_aux_axes(viewlim_mode=None, sharex=host)
par2 = host.get_aux_axes(viewlim_mode=None, sharex=host)
host.axis["right"].set_visible(False)
par1.axis["right"].set_visible(True)
par1.axis["right"].major_ticklabels.set_visible(True)
par1.axis["right"].label.set_visible(True)
par2.axis["right2"] = par2.new_fixed_axis(loc="right", offset=(60, 0))
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
host.set(xlim=(0, 2), ylim=(0, 2), xlabel="Distance", ylabel="Density")
par1.set(ylim=(0, 4), ylabel="Temperature")
par2.set(ylim=(1, 65), ylabel="Velocity")
host.legend()
host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right2"].label.set_color(p3.get_color())
plt.show()
| stable__gallery__axisartist__demo_parasite_axes | 0 | figure_000.png | Parasite Axes demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_parasite_axes.html#sphx-glr-download-gallery-axisartist-demo-parasite-axes-py | https://matplotlib.org/stable/_downloads/5922b9d93b49d592301af79dfdddf7de/demo_parasite_axes.py | demo_parasite_axes.py | axisartist | ok | 1 | null | |
"""
==================
Parasite axis demo
==================
This example demonstrates the use of parasite axis to plot multiple datasets
onto one single plot.
Notice how in this example, *par1* and *par2* are both obtained by calling
``twinx()``, which ties their x-limits with the host's x-axis. From there, each
of those two axis behave separately from each other: different datasets can be
plotted, and the y-limits are adjusted separately.
This approach uses `mpl_toolkits.axes_grid1.parasite_axes.host_subplot` and
`mpl_toolkits.axisartist.axislines.Axes`.
The standard and recommended approach is to use instead standard Matplotlib
axes, as shown in the :doc:`/gallery/spines/multiple_yaxis_with_spines`
example.
An alternative approach using `mpl_toolkits.axes_grid1.parasite_axes.HostAxes`
and `mpl_toolkits.axes_grid1.parasite_axes.ParasiteAxes` is shown in the
:doc:`/gallery/axisartist/demo_parasite_axes` example.
"""
import matplotlib.pyplot as plt
from mpl_toolkits import axisartist
from mpl_toolkits.axes_grid1 import host_subplot
host = host_subplot(111, axes_class=axisartist.Axes)
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
par2.axis["right"] = par2.new_fixed_axis(loc="right", offset=(60, 0))
par1.axis["right"].toggle(all=True)
par2.axis["right"].toggle(all=True)
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
host.set(xlim=(0, 2), ylim=(0, 2), xlabel="Distance", ylabel="Density")
par1.set(ylim=(0, 4), ylabel="Temperature")
par2.set(ylim=(1, 65), ylabel="Velocity")
host.legend()
host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())
plt.show()
| stable__gallery__axisartist__demo_parasite_axes2 | 0 | figure_000.png | Parasite axis demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_parasite_axes2.html#sphx-glr-download-gallery-axisartist-demo-parasite-axes2-py | https://matplotlib.org/stable/_downloads/07a9488814cca10d5122c0c5527bcaaf/demo_parasite_axes2.py | demo_parasite_axes2.py | axisartist | ok | 1 | null | |
"""
===================
Ticklabel alignment
===================
"""
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
def setup_axes(fig, pos):
ax = fig.add_subplot(pos, axes_class=axisartist.Axes)
ax.set_yticks([0.2, 0.8], labels=["short", "loooong"])
ax.set_xticks([0.2, 0.8], labels=[r"$\frac{1}{2}\pi$", r"$\pi$"])
return ax
fig = plt.figure(figsize=(3, 5))
fig.subplots_adjust(left=0.5, hspace=0.7)
ax = setup_axes(fig, 311)
ax.set_ylabel("ha=right")
ax.set_xlabel("va=baseline")
ax = setup_axes(fig, 312)
ax.axis["left"].major_ticklabels.set_ha("center")
ax.axis["bottom"].major_ticklabels.set_va("top")
ax.set_ylabel("ha=center")
ax.set_xlabel("va=top")
ax = setup_axes(fig, 313)
ax.axis["left"].major_ticklabels.set_ha("left")
ax.axis["bottom"].major_ticklabels.set_va("bottom")
ax.set_ylabel("ha=left")
ax.set_xlabel("va=bottom")
plt.show()
| stable__gallery__axisartist__demo_ticklabel_alignment | 0 | figure_000.png | Ticklabel alignment — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_ticklabel_alignment.html#ticklabel-alignment | https://matplotlib.org/stable/_downloads/10139578672ab6e375bdd67b9504f4d6/demo_ticklabel_alignment.py | demo_ticklabel_alignment.py | axisartist | ok | 1 | null | |
"""
===================
Ticklabel direction
===================
"""
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist.axislines as axislines
def setup_axes(fig, pos):
ax = fig.add_subplot(pos, axes_class=axislines.Axes)
ax.set_yticks([0.2, 0.8])
ax.set_xticks([0.2, 0.8])
return ax
fig = plt.figure(figsize=(6, 3))
fig.subplots_adjust(bottom=0.2)
ax = setup_axes(fig, 131)
for axis in ax.axis.values():
axis.major_ticks.set_tick_out(True)
# or you can simply do "ax.axis[:].major_ticks.set_tick_out(True)"
ax = setup_axes(fig, 132)
ax.axis["left"].set_axis_direction("right")
ax.axis["bottom"].set_axis_direction("top")
ax.axis["right"].set_axis_direction("left")
ax.axis["top"].set_axis_direction("bottom")
ax = setup_axes(fig, 133)
ax.axis["left"].set_axis_direction("right")
ax.axis[:].major_ticks.set_tick_out(True)
ax.axis["left"].label.set_text("Long Label Left")
ax.axis["bottom"].label.set_text("Label Bottom")
ax.axis["right"].label.set_text("Long Label Right")
ax.axis["right"].label.set_visible(True)
ax.axis["left"].label.set_pad(0)
ax.axis["bottom"].label.set_pad(10)
plt.show()
| stable__gallery__axisartist__demo_ticklabel_direction | 0 | figure_000.png | Ticklabel direction — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/demo_ticklabel_direction.html#ticklabel-direction | https://matplotlib.org/stable/_downloads/aa167433a0ccdf23a207687a44a29246/demo_ticklabel_direction.py | demo_ticklabel_direction.py | axisartist | ok | 1 | null | |
"""
=====================
Simple axis direction
=====================
"""
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
fig = plt.figure(figsize=(4, 2.5))
ax1 = fig.add_subplot(axes_class=axisartist.Axes)
fig.subplots_adjust(right=0.8)
ax1.axis["left"].major_ticklabels.set_axis_direction("top")
ax1.axis["left"].label.set_text("Left label")
ax1.axis["right"].label.set_visible(True)
ax1.axis["right"].label.set_text("Right label")
ax1.axis["right"].label.set_axis_direction("left")
plt.show()
| stable__gallery__axisartist__simple_axis_direction01 | 0 | figure_000.png | Simple axis direction — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/simple_axis_direction01.html#sphx-glr-download-gallery-axisartist-simple-axis-direction01-py | https://matplotlib.org/stable/_downloads/3b445f30fa702ff55f1547368707c820/simple_axis_direction01.py | simple_axis_direction01.py | axisartist | ok | 1 | null | |
"""
==========================================
Simple axis tick label and tick directions
==========================================
First subplot moves the tick labels to inside the spines.
Second subplot moves the ticks to inside the spines.
These effects can be obtained for a standard Axes by `~.Axes.tick_params`.
"""
import matplotlib.pyplot as plt
import mpl_toolkits.axisartist as axisartist
def setup_axes(fig, pos):
ax = fig.add_subplot(pos, axes_class=axisartist.Axes)
ax.set_yticks([0.2, 0.8])
ax.set_xticks([0.2, 0.8])
return ax
fig = plt.figure(figsize=(5, 2))
fig.subplots_adjust(wspace=0.4, bottom=0.3)
ax1 = setup_axes(fig, 121)
ax1.set_xlabel("ax1 X-label")
ax1.set_ylabel("ax1 Y-label")
ax1.axis[:].invert_ticklabel_direction()
ax2 = setup_axes(fig, 122)
ax2.set_xlabel("ax2 X-label")
ax2.set_ylabel("ax2 Y-label")
ax2.axis[:].major_ticks.set_tick_out(False)
plt.show()
| stable__gallery__axisartist__simple_axis_direction03 | 0 | figure_000.png | Simple axis tick label and tick directions — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/simple_axis_direction03.html#sphx-glr-download-gallery-axisartist-simple-axis-direction03-py | https://matplotlib.org/stable/_downloads/1841cf2985a8e908a9488d1cfc5e6ba3/simple_axis_direction03.py | simple_axis_direction03.py | axisartist | ok | 1 | null | |
"""
===============
Simple axis pad
===============
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D
import mpl_toolkits.axisartist as axisartist
import mpl_toolkits.axisartist.angle_helper as angle_helper
import mpl_toolkits.axisartist.grid_finder as grid_finder
from mpl_toolkits.axisartist.grid_helper_curvelinear import \
GridHelperCurveLinear
def setup_axes(fig, rect):
"""Polar projection, but in a rectangular box."""
# see demo_curvelinear_grid.py for details
tr = Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform(
apply_theta_transforms=False)
extreme_finder = angle_helper.ExtremeFinderCycle(20, 20,
lon_cycle=360,
lat_cycle=None,
lon_minmax=None,
lat_minmax=(0, np.inf),
)
grid_locator1 = angle_helper.LocatorDMS(12)
grid_locator2 = grid_finder.MaxNLocator(5)
tick_formatter1 = angle_helper.FormatterDMS()
grid_helper = GridHelperCurveLinear(tr,
extreme_finder=extreme_finder,
grid_locator1=grid_locator1,
grid_locator2=grid_locator2,
tick_formatter1=tick_formatter1
)
ax1 = fig.add_subplot(
rect, axes_class=axisartist.Axes, grid_helper=grid_helper)
ax1.axis[:].set_visible(False)
ax1.set_aspect(1.)
ax1.set_xlim(-5, 12)
ax1.set_ylim(-5, 10)
return ax1
def add_floating_axis1(ax1):
ax1.axis["lat"] = axis = ax1.new_floating_axis(0, 30)
axis.label.set_text(r"$\theta = 30^{\circ}$")
axis.label.set_visible(True)
return axis
def add_floating_axis2(ax1):
ax1.axis["lon"] = axis = ax1.new_floating_axis(1, 6)
axis.label.set_text(r"$r = 6$")
axis.label.set_visible(True)
return axis
fig = plt.figure(figsize=(9, 3.))
fig.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99,
wspace=0.01, hspace=0.01)
def ann(ax1, d):
if plt.rcParams["text.usetex"]:
d = d.replace("_", r"\_")
ax1.annotate(d, (0.5, 1), (5, -5),
xycoords="axes fraction", textcoords="offset points",
va="top", ha="center")
ax1 = setup_axes(fig, rect=141)
axis = add_floating_axis1(ax1)
ann(ax1, r"default")
ax1 = setup_axes(fig, rect=142)
axis = add_floating_axis1(ax1)
axis.major_ticklabels.set_pad(10)
ann(ax1, r"ticklabels.set_pad(10)")
ax1 = setup_axes(fig, rect=143)
axis = add_floating_axis1(ax1)
axis.label.set_pad(20)
ann(ax1, r"label.set_pad(20)")
ax1 = setup_axes(fig, rect=144)
axis = add_floating_axis1(ax1)
axis.major_ticks.set_tick_out(True)
ann(ax1, "ticks.set_tick_out(True)")
plt.show()
| stable__gallery__axisartist__simple_axis_pad | 0 | figure_000.png | Simple axis pad — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/simple_axis_pad.html#sphx-glr-download-gallery-axisartist-simple-axis-pad-py | https://matplotlib.org/stable/_downloads/6a991ef2680010dc3e315bc57b8de102/simple_axis_pad.py | simple_axis_pad.py | axisartist | ok | 1 | null | |
"""
=============================
Custom spines with axisartist
=============================
This example showcases the use of :mod:`.axisartist` to draw spines at custom
positions (here, at ``y = 0``).
Note, however, that it is simpler to achieve this effect using standard
`.Spine` methods, as demonstrated in
:doc:`/gallery/spines/centered_spines_with_arrows`.
.. redirect-from:: /gallery/axisartist/simple_axisline2
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import axisartist
fig = plt.figure(figsize=(6, 3), layout="constrained")
# To construct Axes of two different classes, we need to use gridspec (or
# MATLAB-style add_subplot calls).
gs = fig.add_gridspec(1, 2)
ax0 = fig.add_subplot(gs[0, 0], axes_class=axisartist.Axes)
# Make a new axis along the first (x) axis which passes through y=0.
ax0.axis["y=0"] = ax0.new_floating_axis(nth_coord=0, value=0,
axis_direction="bottom")
ax0.axis["y=0"].toggle(all=True)
ax0.axis["y=0"].label.set_text("y = 0")
# Make other axis invisible.
ax0.axis["bottom", "top", "right"].set_visible(False)
# Alternatively, one can use AxesZero, which automatically sets up two
# additional axis, named "xzero" (the y=0 axis) and "yzero" (the x=0 axis).
ax1 = fig.add_subplot(gs[0, 1], axes_class=axisartist.axislines.AxesZero)
# "xzero" and "yzero" default to invisible; make xzero axis visible.
ax1.axis["xzero"].set_visible(True)
ax1.axis["xzero"].label.set_text("Axis Zero")
# Make other axis invisible.
ax1.axis["bottom", "top", "right"].set_visible(False)
# Draw some sample data.
x = np.arange(0, 2*np.pi, 0.01)
ax0.plot(x, np.sin(x))
ax1.plot(x, np.sin(x))
plt.show()
| stable__gallery__axisartist__simple_axisartist1 | 0 | figure_000.png | Custom spines with axisartist — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/simple_axisartist1.html#sphx-glr-download-gallery-axisartist-simple-axisartist1-py | https://matplotlib.org/stable/_downloads/172bea947b5b7014a1272376e04e4e51/simple_axisartist1.py | simple_axisartist1.py | axisartist | ok | 1 | null | |
"""
===============
Simple Axisline
===============
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axisartist.axislines import AxesZero
fig = plt.figure()
fig.subplots_adjust(right=0.85)
ax = fig.add_subplot(axes_class=AxesZero)
# make right and top axis invisible
ax.axis["right"].set_visible(False)
ax.axis["top"].set_visible(False)
# make xzero axis (horizontal axis line through y=0) visible.
ax.axis["xzero"].set_visible(True)
ax.axis["xzero"].label.set_text("Axis Zero")
ax.set_ylim(-2, 4)
ax.set_xlabel("Label X")
ax.set_ylabel("Label Y")
# Or:
# ax.axis["bottom"].label.set_text("Label X")
# ax.axis["left"].label.set_text("Label Y")
# make new (right-side) yaxis, but with some offset
ax.axis["right2"] = ax.new_fixed_axis(loc="right", offset=(20, 0))
ax.axis["right2"].label.set_text("Label Y2")
ax.plot([-2, 3, 2])
plt.show()
| stable__gallery__axisartist__simple_axisline | 0 | figure_000.png | Simple Axisline — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/simple_axisline.html#sphx-glr-download-gallery-axisartist-simple-axisline-py | https://matplotlib.org/stable/_downloads/bb682f022912692f490c5c3e20e0b35b/simple_axisline.py | simple_axisline.py | axisartist | ok | 1 | null | |
"""
================
Simple Axisline3
================
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axisartist.axislines import Axes
fig = plt.figure(figsize=(3, 3))
ax = fig.add_subplot(axes_class=Axes)
ax.axis["right"].set_visible(False)
ax.axis["top"].set_visible(False)
plt.show()
| stable__gallery__axisartist__simple_axisline3 | 0 | figure_000.png | Simple Axisline3 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/axisartist/simple_axisline3.html#sphx-glr-download-gallery-axisartist-simple-axisline3-py | https://matplotlib.org/stable/_downloads/364e7f571a4fb87e2fc9de904066c64a/simple_axisline3.py | simple_axisline3.py | axisartist | ok | 1 | null | |
"""
================
Color by y-value
================
Use masked arrays to plot a line with different colors by y-value.
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)
upper = 0.77
lower = -0.77
supper = np.ma.masked_where(s < upper, s)
slower = np.ma.masked_where(s > lower, s)
smiddle = np.ma.masked_where((s < lower) | (s > upper), s)
fig, ax = plt.subplots()
ax.plot(t, smiddle, t, slower, t, supper)
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.plot` / `matplotlib.pyplot.plot`
#
# .. tags::
#
# styling: color
# styling: conditional
# plot-type: line
# level: beginner
| stable__gallery__color__color_by_yvalue | 0 | figure_000.png | Color by y-value — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/color_by_yvalue.html#sphx-glr-download-gallery-color-color-by-yvalue-py | https://matplotlib.org/stable/_downloads/03190594ca1f6702e35730d7e22745c5/color_by_yvalue.py | color_by_yvalue.py | color | ok | 1 | null | |
"""
====================================
Colors in the default property cycle
====================================
Display the colors from the default prop_cycle, which is obtained from the
:ref:`rc parameters<customizing>`.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import TABLEAU_COLORS, same_color
def f(x, a):
"""A nice sigmoid-like parametrized curve, ending approximately at *a*."""
return 0.85 * a * (1 / (1 + np.exp(-x)) + 0.2)
fig, ax = plt.subplots()
ax.axis('off')
ax.set_title("Colors in the default property cycle")
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
x = np.linspace(-4, 4, 200)
for i, (color, color_name) in enumerate(zip(colors, TABLEAU_COLORS)):
assert same_color(color, color_name)
pos = 4.5 - i
ax.plot(x, f(x, pos))
ax.text(4.2, pos, f"'C{i}': '{color_name}'", color=color, va="center")
ax.bar(9, 1, width=1.5, bottom=pos-0.5)
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.axis`
# - `matplotlib.axes.Axes.text`
# - `matplotlib.colors.same_color`
# - `cycler.Cycler`
#
# .. tags::
#
# styling: color
# purpose: reference
# plot-type: line
# level: beginner
| stable__gallery__color__color_cycle_default | 0 | figure_000.png | Colors in the default property cycle — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/color_cycle_default.html#sphx-glr-download-gallery-color-color-cycle-default-py | https://matplotlib.org/stable/_downloads/233af54bee28814ae4bb34817226f0ea/color_cycle_default.py | color_cycle_default.py | color | ok | 1 | null | |
"""
==========
Color Demo
==========
Matplotlib recognizes the following formats to specify a color:
1) an RGB or RGBA tuple of float values in ``[0, 1]`` (e.g. ``(0.1, 0.2, 0.5)``
or ``(0.1, 0.2, 0.5, 0.3)``). RGBA is short for Red, Green, Blue, Alpha;
2) a hex RGB or RGBA string (e.g., ``'#0F0F0F'`` or ``'#0F0F0F0F'``);
3) a shorthand hex RGB or RGBA string, equivalent to the hex RGB or RGBA
string obtained by duplicating each character, (e.g., ``'#abc'``, equivalent
to ``'#aabbcc'``, or ``'#abcd'``, equivalent to ``'#aabbccdd'``);
4) a string representation of a float value in ``[0, 1]`` inclusive for gray
level (e.g., ``'0.5'``);
5) a single letter string, i.e. one of
``{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}``, which are short-hand notations
for shades of blue, green, red, cyan, magenta, yellow, black, and white;
6) a X11/CSS4 ("html") color name, e.g. ``"blue"``;
7) a name from the `xkcd color survey <https://xkcd.com/color/rgb/>`__,
prefixed with ``'xkcd:'`` (e.g., ``'xkcd:sky blue'``);
8) a "Cn" color spec, i.e. ``'C'`` followed by a number, which is an index into
the default property cycle (:rc:`axes.prop_cycle`); the indexing is intended
to occur at rendering time, and defaults to black if the cycle does not
include color.
9) one of ``{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple',
'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}`` which are
the Tableau Colors from the 'tab10' categorical palette (which is the
default color cycle);
For more information on colors in matplotlib see
* the :ref:`colors_def` tutorial;
* the `matplotlib.colors` API;
* the :doc:`/gallery/color/named_colors` example.
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
# 1) RGB tuple:
fig, ax = plt.subplots(facecolor=(.18, .31, .31))
# 2) hex string:
ax.set_facecolor('#eafff5')
# 3) gray level string:
ax.set_title('Voltage vs. time chart', color='0.7')
# 4) single letter color string
ax.set_xlabel('Time [s]', color='c')
# 5) a named color:
ax.set_ylabel('Voltage [mV]', color='peachpuff')
# 6) a named xkcd color:
ax.plot(t, s, 'xkcd:crimson')
# 7) Cn notation:
ax.plot(t, .7*s, color='C4', linestyle='--')
# 8) tab notation:
ax.tick_params(labelcolor='tab:orange')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.plot`
# - `matplotlib.axes.Axes.set_facecolor`
# - `matplotlib.axes.Axes.set_title`
# - `matplotlib.axes.Axes.set_xlabel`
# - `matplotlib.axes.Axes.set_ylabel`
# - `matplotlib.axes.Axes.tick_params`
#
# .. tags::
#
# styling: color
# plot-type: line
# level: beginner
| stable__gallery__color__color_demo | 0 | figure_000.png | Color Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/color_demo.html#sphx-glr-download-gallery-color-color-demo-py | https://matplotlib.org/stable/_downloads/0622457b6b860061b937fd5f8d899da8/color_demo.py | color_demo.py | color | ok | 1 | null | |
"""
=====================
Named color sequences
=====================
Matplotlib's `~matplotlib.colors.ColorSequenceRegistry` allows access to
predefined lists of colors by name e.g.
``colors = matplotlib.color_sequences['Set1']``. This example shows all of the
built in color sequences.
User-defined sequences can be added via `.ColorSequenceRegistry.register`.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
def plot_color_sequences(names, ax):
# Display each named color sequence horizontally on the supplied axes.
for n, name in enumerate(names):
colors = mpl.color_sequences[name]
n_colors = len(colors)
x = np.arange(n_colors)
y = np.full_like(x, n)
ax.scatter(x, y, facecolor=colors, edgecolor='dimgray', s=200, zorder=2)
ax.set_yticks(range(len(names)), labels=names)
ax.grid(visible=True, axis='y')
ax.yaxis.set_inverted(True)
ax.xaxis.set_visible(False)
ax.spines[:].set_visible(False)
ax.tick_params(left=False)
built_in_color_sequences = [
'tab10', 'tab20', 'tab20b', 'tab20c', 'Pastel1', 'Pastel2', 'Paired',
'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'petroff10']
fig, ax = plt.subplots(figsize=(6.4, 9.6), layout='constrained')
plot_color_sequences(built_in_color_sequences, ax)
ax.set_title('Built In Color Sequences')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors.ColorSequenceRegistry`
# - `matplotlib.axes.Axes.scatter`
#
# .. tags::
#
# styling: color
# purpose: reference
| stable__gallery__color__color_sequences | 0 | figure_000.png | Named color sequences — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/color_sequences.html#sphx-glr-download-gallery-color-color-sequences-py | https://matplotlib.org/stable/_downloads/9e70d40e9d045adb66bdd483958508f2/color_sequences.py | color_sequences.py | color | ok | 1 | null | |
"""
========
Colorbar
========
Use `~.Figure.colorbar` by specifying the mappable object (here
the `.AxesImage` returned by `~.axes.Axes.imshow`)
and the Axes to attach the colorbar to.
"""
import matplotlib.pyplot as plt
import numpy as np
# setup some generic data
N = 37
x, y = np.mgrid[:N, :N]
Z = (np.cos(x*0.2) + np.sin(y*0.3))
# mask out the negative and positive values, respectively
Zpos = np.ma.masked_less(Z, 0)
Zneg = np.ma.masked_greater(Z, 0)
fig, (ax1, ax2, ax3) = plt.subplots(figsize=(13, 3), ncols=3)
# plot just the positive data and save the
# color "mappable" object returned by ax1.imshow
pos = ax1.imshow(Zpos, cmap='Blues', interpolation='none')
# add the colorbar using the figure's method,
# telling which mappable we're talking about and
# which Axes object it should be near
fig.colorbar(pos, ax=ax1)
# repeat everything above for the negative data
# you can specify location, anchor and shrink the colorbar
neg = ax2.imshow(Zneg, cmap='Reds_r', interpolation='none')
fig.colorbar(neg, ax=ax2, location='right', anchor=(0, 0.3), shrink=0.7)
# Plot both positive and negative values between +/- 1.2
pos_neg_clipped = ax3.imshow(Z, cmap='RdBu', vmin=-1.2, vmax=1.2,
interpolation='none')
# Add minorticks on the colorbar to make it easy to read the
# values off the colorbar.
cbar = fig.colorbar(pos_neg_clipped, ax=ax3, extend='both')
cbar.minorticks_on()
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.imshow` / `matplotlib.pyplot.imshow`
# - `matplotlib.figure.Figure.colorbar` / `matplotlib.pyplot.colorbar`
# - `matplotlib.colorbar.Colorbar.minorticks_on`
# - `matplotlib.colorbar.Colorbar.minorticks_off`
#
# .. tags::
#
# component: colorbar
# styling: color
# plot-type: imshow
# level: beginner
| stable__gallery__color__colorbar_basics | 0 | figure_000.png | Colorbar — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colorbar_basics.html#sphx-glr-download-gallery-color-colorbar-basics-py | https://matplotlib.org/stable/_downloads/642498711ab58d6f80ef376a375dda14/colorbar_basics.py | colorbar_basics.py | color | ok | 1 | null | |
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
A reversed version of each of these colormaps is available by appending
``_r`` to the name, as shown in :ref:`reverse-cmap`.
See :ref:`colormaps` for an in-depth discussion about
colormaps, including colorblind-friendliness, and
:ref:`colormap-manipulation` for a guide to creating
colormaps.
"""
import matplotlib.pyplot as plt
import numpy as np
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)
axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)
for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
# %%
# .. _reverse-cmap:
#
# Reversed colormaps
# ------------------
#
# Append ``_r`` to the name of any built-in colormap to get the reversed
# version:
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])
# %%
# The built-in reversed colormaps are generated using `.Colormap.reversed`.
# For an example, see :ref:`reversing-colormap`
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.imshow`
# - `matplotlib.figure.Figure.text`
# - `matplotlib.axes.Axes.set_axis_off`
#
# .. tags::
#
# styling: colormap
# purpose: reference
| stable__gallery__color__colormap_reference | 0 | figure_000.png | Colormap reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-download-gallery-color-colormap-reference-py | https://matplotlib.org/stable/_downloads/dd314a83577f446493e34d27a1ed8451/colormap_reference.py | colormap_reference.py | color | ok | 8 | null | |
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
A reversed version of each of these colormaps is available by appending
``_r`` to the name, as shown in :ref:`reverse-cmap`.
See :ref:`colormaps` for an in-depth discussion about
colormaps, including colorblind-friendliness, and
:ref:`colormap-manipulation` for a guide to creating
colormaps.
"""
import matplotlib.pyplot as plt
import numpy as np
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)
axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)
for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
# %%
# .. _reverse-cmap:
#
# Reversed colormaps
# ------------------
#
# Append ``_r`` to the name of any built-in colormap to get the reversed
# version:
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])
# %%
# The built-in reversed colormaps are generated using `.Colormap.reversed`.
# For an example, see :ref:`reversing-colormap`
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.imshow`
# - `matplotlib.figure.Figure.text`
# - `matplotlib.axes.Axes.set_axis_off`
#
# .. tags::
#
# styling: colormap
# purpose: reference
| stable__gallery__color__colormap_reference | 1 | figure_001.png | Colormap reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-download-gallery-color-colormap-reference-py | https://matplotlib.org/stable/_downloads/dd314a83577f446493e34d27a1ed8451/colormap_reference.py | colormap_reference.py | color | ok | 8 | null | |
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
A reversed version of each of these colormaps is available by appending
``_r`` to the name, as shown in :ref:`reverse-cmap`.
See :ref:`colormaps` for an in-depth discussion about
colormaps, including colorblind-friendliness, and
:ref:`colormap-manipulation` for a guide to creating
colormaps.
"""
import matplotlib.pyplot as plt
import numpy as np
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)
axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)
for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
# %%
# .. _reverse-cmap:
#
# Reversed colormaps
# ------------------
#
# Append ``_r`` to the name of any built-in colormap to get the reversed
# version:
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])
# %%
# The built-in reversed colormaps are generated using `.Colormap.reversed`.
# For an example, see :ref:`reversing-colormap`
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.imshow`
# - `matplotlib.figure.Figure.text`
# - `matplotlib.axes.Axes.set_axis_off`
#
# .. tags::
#
# styling: colormap
# purpose: reference
| stable__gallery__color__colormap_reference | 2 | figure_002.png | Colormap reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-download-gallery-color-colormap-reference-py | https://matplotlib.org/stable/_downloads/dd314a83577f446493e34d27a1ed8451/colormap_reference.py | colormap_reference.py | color | ok | 8 | null | |
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
A reversed version of each of these colormaps is available by appending
``_r`` to the name, as shown in :ref:`reverse-cmap`.
See :ref:`colormaps` for an in-depth discussion about
colormaps, including colorblind-friendliness, and
:ref:`colormap-manipulation` for a guide to creating
colormaps.
"""
import matplotlib.pyplot as plt
import numpy as np
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)
axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)
for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
# %%
# .. _reverse-cmap:
#
# Reversed colormaps
# ------------------
#
# Append ``_r`` to the name of any built-in colormap to get the reversed
# version:
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])
# %%
# The built-in reversed colormaps are generated using `.Colormap.reversed`.
# For an example, see :ref:`reversing-colormap`
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.imshow`
# - `matplotlib.figure.Figure.text`
# - `matplotlib.axes.Axes.set_axis_off`
#
# .. tags::
#
# styling: colormap
# purpose: reference
| stable__gallery__color__colormap_reference | 3 | figure_003.png | Colormap reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-download-gallery-color-colormap-reference-py | https://matplotlib.org/stable/_downloads/dd314a83577f446493e34d27a1ed8451/colormap_reference.py | colormap_reference.py | color | ok | 8 | null | |
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
A reversed version of each of these colormaps is available by appending
``_r`` to the name, as shown in :ref:`reverse-cmap`.
See :ref:`colormaps` for an in-depth discussion about
colormaps, including colorblind-friendliness, and
:ref:`colormap-manipulation` for a guide to creating
colormaps.
"""
import matplotlib.pyplot as plt
import numpy as np
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)
axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)
for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
# %%
# .. _reverse-cmap:
#
# Reversed colormaps
# ------------------
#
# Append ``_r`` to the name of any built-in colormap to get the reversed
# version:
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])
# %%
# The built-in reversed colormaps are generated using `.Colormap.reversed`.
# For an example, see :ref:`reversing-colormap`
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.imshow`
# - `matplotlib.figure.Figure.text`
# - `matplotlib.axes.Axes.set_axis_off`
#
# .. tags::
#
# styling: colormap
# purpose: reference
| stable__gallery__color__colormap_reference | 4 | figure_004.png | Colormap reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-download-gallery-color-colormap-reference-py | https://matplotlib.org/stable/_downloads/dd314a83577f446493e34d27a1ed8451/colormap_reference.py | colormap_reference.py | color | ok | 8 | null | |
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
A reversed version of each of these colormaps is available by appending
``_r`` to the name, as shown in :ref:`reverse-cmap`.
See :ref:`colormaps` for an in-depth discussion about
colormaps, including colorblind-friendliness, and
:ref:`colormap-manipulation` for a guide to creating
colormaps.
"""
import matplotlib.pyplot as plt
import numpy as np
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)
axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)
for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
# %%
# .. _reverse-cmap:
#
# Reversed colormaps
# ------------------
#
# Append ``_r`` to the name of any built-in colormap to get the reversed
# version:
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])
# %%
# The built-in reversed colormaps are generated using `.Colormap.reversed`.
# For an example, see :ref:`reversing-colormap`
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.imshow`
# - `matplotlib.figure.Figure.text`
# - `matplotlib.axes.Axes.set_axis_off`
#
# .. tags::
#
# styling: colormap
# purpose: reference
| stable__gallery__color__colormap_reference | 5 | figure_005.png | Colormap reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-download-gallery-color-colormap-reference-py | https://matplotlib.org/stable/_downloads/dd314a83577f446493e34d27a1ed8451/colormap_reference.py | colormap_reference.py | color | ok | 8 | null | |
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
A reversed version of each of these colormaps is available by appending
``_r`` to the name, as shown in :ref:`reverse-cmap`.
See :ref:`colormaps` for an in-depth discussion about
colormaps, including colorblind-friendliness, and
:ref:`colormap-manipulation` for a guide to creating
colormaps.
"""
import matplotlib.pyplot as plt
import numpy as np
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)
axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)
for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
# %%
# .. _reverse-cmap:
#
# Reversed colormaps
# ------------------
#
# Append ``_r`` to the name of any built-in colormap to get the reversed
# version:
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])
# %%
# The built-in reversed colormaps are generated using `.Colormap.reversed`.
# For an example, see :ref:`reversing-colormap`
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.imshow`
# - `matplotlib.figure.Figure.text`
# - `matplotlib.axes.Axes.set_axis_off`
#
# .. tags::
#
# styling: colormap
# purpose: reference
| stable__gallery__color__colormap_reference | 6 | figure_006.png | Colormap reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-download-gallery-color-colormap-reference-py | https://matplotlib.org/stable/_downloads/dd314a83577f446493e34d27a1ed8451/colormap_reference.py | colormap_reference.py | color | ok | 8 | null | |
"""
==================
Colormap reference
==================
Reference for colormaps included with Matplotlib.
A reversed version of each of these colormaps is available by appending
``_r`` to the name, as shown in :ref:`reverse-cmap`.
See :ref:`colormaps` for an in-depth discussion about
colormaps, including colorblind-friendliness, and
:ref:`colormap-manipulation` for a guide to creating
colormaps.
"""
import matplotlib.pyplot as plt
import numpy as np
cmaps = [('Perceptually Uniform Sequential', [
'viridis', 'plasma', 'inferno', 'magma', 'cividis']),
('Sequential', [
'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']),
('Sequential (2)', [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'hot', 'afmhot', 'gist_heat', 'copper']),
('Diverging', [
'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic',
'berlin', 'managua', 'vanimo']),
('Cyclic', ['twilight', 'twilight_shifted', 'hsv']),
('Qualitative', [
'Pastel1', 'Pastel2', 'Paired', 'Accent',
'Dark2', 'Set1', 'Set2', 'Set3',
'tab10', 'tab20', 'tab20b', 'tab20c']),
('Miscellaneous', [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'cubehelix', 'brg',
'gist_rainbow', 'rainbow', 'jet', 'turbo', 'nipy_spectral',
'gist_ncar'])]
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
# Create figure and adjust figure height to number of colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows-1)*0.1)*0.22
fig, axs = plt.subplots(nrows=nrows, figsize=(6.4, figh))
fig.subplots_adjust(top=1-.35/figh, bottom=.15/figh, left=0.2, right=0.99)
axs[0].set_title(f"{cmap_category} colormaps", fontsize=14)
for ax, cmap_name in zip(axs, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=cmap_name)
ax.text(-.01, .5, cmap_name, va='center', ha='right', fontsize=10,
transform=ax.transAxes)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axs:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
# %%
# .. _reverse-cmap:
#
# Reversed colormaps
# ------------------
#
# Append ``_r`` to the name of any built-in colormap to get the reversed
# version:
plot_color_gradients("Original and reversed ", ['viridis', 'viridis_r'])
# %%
# The built-in reversed colormaps are generated using `.Colormap.reversed`.
# For an example, see :ref:`reversing-colormap`
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.axes.Axes.imshow`
# - `matplotlib.figure.Figure.text`
# - `matplotlib.axes.Axes.set_axis_off`
#
# .. tags::
#
# styling: colormap
# purpose: reference
| stable__gallery__color__colormap_reference | 7 | figure_007.png | Colormap reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/colormap_reference.html#sphx-glr-download-gallery-color-colormap-reference-py | https://matplotlib.org/stable/_downloads/dd314a83577f446493e34d27a1ed8451/colormap_reference.py | colormap_reference.py | color | ok | 8 | null | |
"""
=======================================
Create a colormap from a list of colors
=======================================
For more detail on creating and manipulating colormaps see
:ref:`colormap-manipulation`.
Creating a :ref:`colormap <colormaps>` from a list of colors
can be done with the `.LinearSegmentedColormap.from_list` method. You must
pass a list of RGB tuples that define the mixture of colors from 0 to 1.
Creating custom colormaps
=========================
It is also possible to create a custom mapping for a colormap. This is
accomplished by creating dictionary that specifies how the RGB channels
change from one end of the cmap to the other.
Example: suppose you want red to increase from 0 to 1 over the bottom
half, green to do the same over the middle half, and blue over the top
half. Then you would use::
cdict = {
'red': (
(0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0),
),
'blue': (
(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0),
)
}
If, as in this example, there are no discontinuities in the r, g, and b
components, then it is quite simple: the second and third element of
each tuple, above, is the same -- call it "``y``". The first element ("``x``")
defines interpolation intervals over the full range of 0 to 1, and it
must span that whole range. In other words, the values of ``x`` divide the
0-to-1 range into a set of segments, and ``y`` gives the end-point color
values for each segment.
Now consider the green, ``cdict['green']`` is saying that for:
- 0 <= ``x`` <= 0.25, ``y`` is zero; no green.
- 0.25 < ``x`` <= 0.75, ``y`` varies linearly from 0 to 1.
- 0.75 < ``x`` <= 1, ``y`` remains at 1, full green.
If there are discontinuities, then it is a little more complicated. Label the 3
elements in each row in the ``cdict`` entry for a given color as ``(x, y0,
y1)``. Then for values of ``x`` between ``x[i]`` and ``x[i+1]`` the color value
is interpolated between ``y1[i]`` and ``y0[i+1]``.
Going back to a cookbook example::
cdict = {
'red': (
(0.0, 0.0, 0.0),
(0.5, 1.0, 0.7),
(1.0, 1.0, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(0.5, 1.0, 0.0),
(1.0, 1.0, 1.0),
),
'blue': (
(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0),
)
}
and look at ``cdict['red'][1]``; because ``y0 != y1``, it is saying that for
``x`` from 0 to 0.5, red increases from 0 to 1, but then it jumps down, so that
for ``x`` from 0.5 to 1, red increases from 0.7 to 1. Green ramps from 0 to 1
as ``x`` goes from 0 to 0.5, then jumps back to 0, and ramps back to 1 as ``x``
goes from 0.5 to 1. ::
row i: x y0 y1
/
/
row i+1: x y0 y1
Above is an attempt to show that for ``x`` in the range ``x[i]`` to ``x[i+1]``,
the interpolation is between ``y1[i]`` and ``y0[i+1]``. So, ``y0[0]`` and
``y1[-1]`` are never used.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap
# Make some illustrative fake data:
x = np.arange(0, np.pi, 0.1)
y = np.arange(0, 2 * np.pi, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.sin(Y) * 10
# %%
# Colormaps from a list
# ---------------------
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B
n_bins = [3, 6, 10, 100] # Discretizes the interpolation into bins
cmap_name = 'my_list'
fig, axs = plt.subplots(2, 2, figsize=(6, 9))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)
for n_bin, ax in zip(n_bins, axs.flat):
# Create the colormap
cmap = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bin)
# Fewer bins will result in "coarser" colomap interpolation
im = ax.imshow(Z, origin='lower', cmap=cmap)
ax.set_title("N bins: %s" % n_bin)
fig.colorbar(im, ax=ax)
# %%
# Custom colormaps
# ----------------
cdict1 = {
'red': (
(0.0, 0.0, 0.0),
(0.5, 0.0, 0.1),
(1.0, 1.0, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0),
),
'blue': (
(0.0, 0.0, 1.0),
(0.5, 0.1, 0.0),
(1.0, 0.0, 0.0),
)
}
cdict2 = {
'red': (
(0.0, 0.0, 0.0),
(0.5, 0.0, 1.0),
(1.0, 0.1, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0),
),
'blue': (
(0.0, 0.0, 0.1),
(0.5, 1.0, 0.0),
(1.0, 0.0, 0.0),
)
}
cdict3 = {
'red': (
(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.5, 0.8, 1.0),
(0.75, 1.0, 1.0),
(1.0, 0.4, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.5, 0.9, 0.9),
(0.75, 0.0, 0.0),
(1.0, 0.0, 0.0),
),
'blue': (
(0.0, 0.0, 0.4),
(0.25, 1.0, 1.0),
(0.5, 1.0, 0.8),
(0.75, 0.0, 0.0),
(1.0, 0.0, 0.0),
)
}
# Make a modified version of cdict3 with some transparency
# in the middle of the range.
cdict4 = {
**cdict3,
'alpha': (
(0.0, 1.0, 1.0),
# (0.25, 1.0, 1.0),
(0.5, 0.3, 0.3),
# (0.75, 1.0, 1.0),
(1.0, 1.0, 1.0),
),
}
# %%
# Now we will use this example to illustrate 2 ways of
# handling custom colormaps.
# First, the most direct and explicit:
blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1)
# %%
# Second, create the map explicitly and register it.
# Like the first method, this method works with any kind
# of Colormap, not just
# a LinearSegmentedColormap:
mpl.colormaps.register(LinearSegmentedColormap('BlueRed2', cdict2))
mpl.colormaps.register(LinearSegmentedColormap('BlueRed3', cdict3))
mpl.colormaps.register(LinearSegmentedColormap('BlueRedAlpha', cdict4))
# %%
# Make the figure, with 4 subplots:
fig, axs = plt.subplots(2, 2, figsize=(6, 9))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)
im1 = axs[0, 0].imshow(Z, cmap=blue_red1)
fig.colorbar(im1, ax=axs[0, 0])
im2 = axs[1, 0].imshow(Z, cmap='BlueRed2')
fig.colorbar(im2, ax=axs[1, 0])
# Now we will set the third cmap as the default. One would
# not normally do this in the middle of a script like this;
# it is done here just to illustrate the method.
plt.rcParams['image.cmap'] = 'BlueRed3'
im3 = axs[0, 1].imshow(Z)
fig.colorbar(im3, ax=axs[0, 1])
axs[0, 1].set_title("Alpha = 1")
# Or as yet another variation, we can replace the rcParams
# specification *before* the imshow with the following *after*
# imshow.
# This sets the new default *and* sets the colormap of the last
# image-like item plotted via pyplot, if any.
#
# Draw a line with low zorder so it will be behind the image.
axs[1, 1].plot([0, 10 * np.pi], [0, 20 * np.pi], color='c', lw=20, zorder=-1)
im4 = axs[1, 1].imshow(Z)
fig.colorbar(im4, ax=axs[1, 1])
# Here it is: changing the colormap for the current image and its
# colorbar after they have been plotted.
im4.set_cmap('BlueRedAlpha')
axs[1, 1].set_title("Varying alpha")
fig.suptitle('Custom Blue-Red colormaps', fontsize=16)
fig.subplots_adjust(top=0.9)
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.imshow` / `matplotlib.pyplot.imshow`
# - `matplotlib.figure.Figure.colorbar` / `matplotlib.pyplot.colorbar`
# - `matplotlib.colors`
# - `matplotlib.colors.LinearSegmentedColormap`
# - `matplotlib.colors.LinearSegmentedColormap.from_list`
# - `matplotlib.cm`
# - `matplotlib.cm.ScalarMappable.set_cmap`
# - `matplotlib.cm.ColormapRegistry.register`
#
# .. tags::
#
# styling: colormap
# plot-type: imshow
# level: intermediate
| stable__gallery__color__custom_cmap | 0 | figure_000.png | Create a colormap from a list of colors — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/custom_cmap.html#sphx-glr-download-gallery-color-custom-cmap-py | https://matplotlib.org/stable/_downloads/fba15be770735fdb1b9272eaaf80104e/custom_cmap.py | custom_cmap.py | color | ok | 2 | null | |
"""
=======================================
Create a colormap from a list of colors
=======================================
For more detail on creating and manipulating colormaps see
:ref:`colormap-manipulation`.
Creating a :ref:`colormap <colormaps>` from a list of colors
can be done with the `.LinearSegmentedColormap.from_list` method. You must
pass a list of RGB tuples that define the mixture of colors from 0 to 1.
Creating custom colormaps
=========================
It is also possible to create a custom mapping for a colormap. This is
accomplished by creating dictionary that specifies how the RGB channels
change from one end of the cmap to the other.
Example: suppose you want red to increase from 0 to 1 over the bottom
half, green to do the same over the middle half, and blue over the top
half. Then you would use::
cdict = {
'red': (
(0.0, 0.0, 0.0),
(0.5, 1.0, 1.0),
(1.0, 1.0, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.75, 1.0, 1.0),
(1.0, 1.0, 1.0),
),
'blue': (
(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0),
)
}
If, as in this example, there are no discontinuities in the r, g, and b
components, then it is quite simple: the second and third element of
each tuple, above, is the same -- call it "``y``". The first element ("``x``")
defines interpolation intervals over the full range of 0 to 1, and it
must span that whole range. In other words, the values of ``x`` divide the
0-to-1 range into a set of segments, and ``y`` gives the end-point color
values for each segment.
Now consider the green, ``cdict['green']`` is saying that for:
- 0 <= ``x`` <= 0.25, ``y`` is zero; no green.
- 0.25 < ``x`` <= 0.75, ``y`` varies linearly from 0 to 1.
- 0.75 < ``x`` <= 1, ``y`` remains at 1, full green.
If there are discontinuities, then it is a little more complicated. Label the 3
elements in each row in the ``cdict`` entry for a given color as ``(x, y0,
y1)``. Then for values of ``x`` between ``x[i]`` and ``x[i+1]`` the color value
is interpolated between ``y1[i]`` and ``y0[i+1]``.
Going back to a cookbook example::
cdict = {
'red': (
(0.0, 0.0, 0.0),
(0.5, 1.0, 0.7),
(1.0, 1.0, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(0.5, 1.0, 0.0),
(1.0, 1.0, 1.0),
),
'blue': (
(0.0, 0.0, 0.0),
(0.5, 0.0, 0.0),
(1.0, 1.0, 1.0),
)
}
and look at ``cdict['red'][1]``; because ``y0 != y1``, it is saying that for
``x`` from 0 to 0.5, red increases from 0 to 1, but then it jumps down, so that
for ``x`` from 0.5 to 1, red increases from 0.7 to 1. Green ramps from 0 to 1
as ``x`` goes from 0 to 0.5, then jumps back to 0, and ramps back to 1 as ``x``
goes from 0.5 to 1. ::
row i: x y0 y1
/
/
row i+1: x y0 y1
Above is an attempt to show that for ``x`` in the range ``x[i]`` to ``x[i+1]``,
the interpolation is between ``y1[i]`` and ``y0[i+1]``. So, ``y0[0]`` and
``y1[-1]`` are never used.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from matplotlib.colors import LinearSegmentedColormap
# Make some illustrative fake data:
x = np.arange(0, np.pi, 0.1)
y = np.arange(0, 2 * np.pi, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.sin(Y) * 10
# %%
# Colormaps from a list
# ---------------------
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B
n_bins = [3, 6, 10, 100] # Discretizes the interpolation into bins
cmap_name = 'my_list'
fig, axs = plt.subplots(2, 2, figsize=(6, 9))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)
for n_bin, ax in zip(n_bins, axs.flat):
# Create the colormap
cmap = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bin)
# Fewer bins will result in "coarser" colomap interpolation
im = ax.imshow(Z, origin='lower', cmap=cmap)
ax.set_title("N bins: %s" % n_bin)
fig.colorbar(im, ax=ax)
# %%
# Custom colormaps
# ----------------
cdict1 = {
'red': (
(0.0, 0.0, 0.0),
(0.5, 0.0, 0.1),
(1.0, 1.0, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0),
),
'blue': (
(0.0, 0.0, 1.0),
(0.5, 0.1, 0.0),
(1.0, 0.0, 0.0),
)
}
cdict2 = {
'red': (
(0.0, 0.0, 0.0),
(0.5, 0.0, 1.0),
(1.0, 0.1, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0),
),
'blue': (
(0.0, 0.0, 0.1),
(0.5, 1.0, 0.0),
(1.0, 0.0, 0.0),
)
}
cdict3 = {
'red': (
(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.5, 0.8, 1.0),
(0.75, 1.0, 1.0),
(1.0, 0.4, 1.0),
),
'green': (
(0.0, 0.0, 0.0),
(0.25, 0.0, 0.0),
(0.5, 0.9, 0.9),
(0.75, 0.0, 0.0),
(1.0, 0.0, 0.0),
),
'blue': (
(0.0, 0.0, 0.4),
(0.25, 1.0, 1.0),
(0.5, 1.0, 0.8),
(0.75, 0.0, 0.0),
(1.0, 0.0, 0.0),
)
}
# Make a modified version of cdict3 with some transparency
# in the middle of the range.
cdict4 = {
**cdict3,
'alpha': (
(0.0, 1.0, 1.0),
# (0.25, 1.0, 1.0),
(0.5, 0.3, 0.3),
# (0.75, 1.0, 1.0),
(1.0, 1.0, 1.0),
),
}
# %%
# Now we will use this example to illustrate 2 ways of
# handling custom colormaps.
# First, the most direct and explicit:
blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1)
# %%
# Second, create the map explicitly and register it.
# Like the first method, this method works with any kind
# of Colormap, not just
# a LinearSegmentedColormap:
mpl.colormaps.register(LinearSegmentedColormap('BlueRed2', cdict2))
mpl.colormaps.register(LinearSegmentedColormap('BlueRed3', cdict3))
mpl.colormaps.register(LinearSegmentedColormap('BlueRedAlpha', cdict4))
# %%
# Make the figure, with 4 subplots:
fig, axs = plt.subplots(2, 2, figsize=(6, 9))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)
im1 = axs[0, 0].imshow(Z, cmap=blue_red1)
fig.colorbar(im1, ax=axs[0, 0])
im2 = axs[1, 0].imshow(Z, cmap='BlueRed2')
fig.colorbar(im2, ax=axs[1, 0])
# Now we will set the third cmap as the default. One would
# not normally do this in the middle of a script like this;
# it is done here just to illustrate the method.
plt.rcParams['image.cmap'] = 'BlueRed3'
im3 = axs[0, 1].imshow(Z)
fig.colorbar(im3, ax=axs[0, 1])
axs[0, 1].set_title("Alpha = 1")
# Or as yet another variation, we can replace the rcParams
# specification *before* the imshow with the following *after*
# imshow.
# This sets the new default *and* sets the colormap of the last
# image-like item plotted via pyplot, if any.
#
# Draw a line with low zorder so it will be behind the image.
axs[1, 1].plot([0, 10 * np.pi], [0, 20 * np.pi], color='c', lw=20, zorder=-1)
im4 = axs[1, 1].imshow(Z)
fig.colorbar(im4, ax=axs[1, 1])
# Here it is: changing the colormap for the current image and its
# colorbar after they have been plotted.
im4.set_cmap('BlueRedAlpha')
axs[1, 1].set_title("Varying alpha")
fig.suptitle('Custom Blue-Red colormaps', fontsize=16)
fig.subplots_adjust(top=0.9)
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.imshow` / `matplotlib.pyplot.imshow`
# - `matplotlib.figure.Figure.colorbar` / `matplotlib.pyplot.colorbar`
# - `matplotlib.colors`
# - `matplotlib.colors.LinearSegmentedColormap`
# - `matplotlib.colors.LinearSegmentedColormap.from_list`
# - `matplotlib.cm`
# - `matplotlib.cm.ScalarMappable.set_cmap`
# - `matplotlib.cm.ColormapRegistry.register`
#
# .. tags::
#
# styling: colormap
# plot-type: imshow
# level: intermediate
| stable__gallery__color__custom_cmap | 1 | figure_001.png | Create a colormap from a list of colors — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/custom_cmap.html#sphx-glr-download-gallery-color-custom-cmap-py | https://matplotlib.org/stable/_downloads/fba15be770735fdb1b9272eaaf80104e/custom_cmap.py | custom_cmap.py | color | ok | 2 | null | |
"""
===========================================
Selecting individual colors from a colormap
===========================================
Sometimes we want to use more colors or a different set of colors than the default color
cycle provides. Selecting individual colors from one of the provided colormaps can be a
convenient way to do this.
We can retrieve colors from any `.Colormap` by calling it with a float or a list of
floats in the range [0, 1]; e.g. ``cmap(0.5)`` will give the middle color. See also
`.Colormap.__call__`.
Extracting colors from a continuous colormap
--------------------------------------------
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
n_lines = 21
cmap = mpl.colormaps['plasma']
# Take colors at regular intervals spanning the colormap.
colors = cmap(np.linspace(0, 1, n_lines))
fig, ax = plt.subplots(layout='constrained')
for i, color in enumerate(colors):
ax.plot([0, i], color=color)
plt.show()
# %%
#
# Extracting colors from a discrete colormap
# ------------------------------------------
# The list of all colors in a `.ListedColormap` is available as the ``colors``
# attribute. Note that all the colors from Matplotlib's qualitative color maps
# are also available as color sequences, so may be accessed more directly from
# the color sequence registry. See :doc:`/gallery/color/color_sequences`.
colors = mpl.colormaps['Dark2'].colors
fig, ax = plt.subplots(layout='constrained')
for i, color in enumerate(colors):
ax.plot([0, i], color=color)
plt.show()
# %%
# See Also
# --------
#
# For more details about manipulating colormaps, see :ref:`colormap-manipulation`. To
# change the default color cycle, see :ref:`color_cycle`.
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors.Colormap`
# - `matplotlib.colors.Colormap.resampled`
#
# .. tags::
#
# component: colormap
# styling: color
# plot-type: line
# level: intermediate
| stable__gallery__color__individual_colors_from_cmap | 0 | figure_000.png | Selecting individual colors from a colormap — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/individual_colors_from_cmap.html#sphx-glr-download-gallery-color-individual-colors-from-cmap-py | https://matplotlib.org/stable/_downloads/b1c9924f6057db5fd639115816c61470/individual_colors_from_cmap.py | individual_colors_from_cmap.py | color | ok | 2 | null | |
"""
====================
List of named colors
====================
This plots a list of the named colors supported by Matplotlib.
For more information on colors in matplotlib see
* the :ref:`colors_def` tutorial;
* the `matplotlib.colors` API;
* the :doc:`/gallery/color/color_demo`.
----------------------------
Helper Function for Plotting
----------------------------
First we define a helper function for making a table of colors, then we use it
on some common color categories.
"""
import math
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Rectangle
def plot_colortable(colors, *, ncols=4, sort_colors=True):
cell_width = 212
cell_height = 22
swatch_width = 48
margin = 12
# Sort colors by hue, saturation, value and name.
if sort_colors is True:
names = sorted(
colors, key=lambda c: tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(c))))
else:
names = list(colors)
n = len(names)
nrows = math.ceil(n / ncols)
width = cell_width * ncols + 2 * margin
height = cell_height * nrows + 2 * margin
dpi = 72
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
fig.subplots_adjust(margin/width, margin/height,
(width-margin)/width, (height-margin)/height)
ax.set_xlim(0, cell_width * ncols)
ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
ax.yaxis.set_visible(False)
ax.xaxis.set_visible(False)
ax.set_axis_off()
for i, name in enumerate(names):
row = i % nrows
col = i // nrows
y = row * cell_height
swatch_start_x = cell_width * col
text_pos_x = cell_width * col + swatch_width + 7
ax.text(text_pos_x, y, name, fontsize=14,
horizontalalignment='left',
verticalalignment='center')
ax.add_patch(
Rectangle(xy=(swatch_start_x, y-9), width=swatch_width,
height=18, facecolor=colors[name], edgecolor='0.7')
)
return fig
# %%
# -----------
# Base colors
# -----------
plot_colortable(mcolors.BASE_COLORS, ncols=3, sort_colors=False)
# %%
# ---------------
# Tableau Palette
# ---------------
plot_colortable(mcolors.TABLEAU_COLORS, ncols=2, sort_colors=False)
# %%
# ----------
# CSS Colors
# ----------
# sphinx_gallery_thumbnail_number = 3
plot_colortable(mcolors.CSS4_COLORS)
plt.show()
# %%
# -----------
# XKCD Colors
# -----------
# Matplotlib supports colors from the
# `xkcd color survey <https://xkcd.com/color/rgb/>`_, e.g. ``"xkcd:sky blue"``. Since
# this contains almost 1000 colors, a figure of this would be very large and is thus
# omitted here. You can use the following code to generate the overview yourself ::
#
# xkcd_fig = plot_colortable(mcolors.XKCD_COLORS)
# xkcd_fig.savefig("XKCD_Colors.png")
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.colors.rgb_to_hsv`
# - `matplotlib.colors.to_rgba`
# - `matplotlib.figure.Figure.get_size_inches`
# - `matplotlib.figure.Figure.subplots_adjust`
# - `matplotlib.axes.Axes.text`
# - `matplotlib.patches.Rectangle`
#
# .. tags::
#
# styling: color
# purpose: reference
| stable__gallery__color__named_colors | 0 | figure_000.png | List of named colors — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/named_colors.html#xkcd-colors | https://matplotlib.org/stable/_downloads/861cf0b07b083f3c44ddd625a0e99000/named_colors.py | named_colors.py | color | ok | 3 | null | |
"""
====================
List of named colors
====================
This plots a list of the named colors supported by Matplotlib.
For more information on colors in matplotlib see
* the :ref:`colors_def` tutorial;
* the `matplotlib.colors` API;
* the :doc:`/gallery/color/color_demo`.
----------------------------
Helper Function for Plotting
----------------------------
First we define a helper function for making a table of colors, then we use it
on some common color categories.
"""
import math
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Rectangle
def plot_colortable(colors, *, ncols=4, sort_colors=True):
cell_width = 212
cell_height = 22
swatch_width = 48
margin = 12
# Sort colors by hue, saturation, value and name.
if sort_colors is True:
names = sorted(
colors, key=lambda c: tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(c))))
else:
names = list(colors)
n = len(names)
nrows = math.ceil(n / ncols)
width = cell_width * ncols + 2 * margin
height = cell_height * nrows + 2 * margin
dpi = 72
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
fig.subplots_adjust(margin/width, margin/height,
(width-margin)/width, (height-margin)/height)
ax.set_xlim(0, cell_width * ncols)
ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
ax.yaxis.set_visible(False)
ax.xaxis.set_visible(False)
ax.set_axis_off()
for i, name in enumerate(names):
row = i % nrows
col = i // nrows
y = row * cell_height
swatch_start_x = cell_width * col
text_pos_x = cell_width * col + swatch_width + 7
ax.text(text_pos_x, y, name, fontsize=14,
horizontalalignment='left',
verticalalignment='center')
ax.add_patch(
Rectangle(xy=(swatch_start_x, y-9), width=swatch_width,
height=18, facecolor=colors[name], edgecolor='0.7')
)
return fig
# %%
# -----------
# Base colors
# -----------
plot_colortable(mcolors.BASE_COLORS, ncols=3, sort_colors=False)
# %%
# ---------------
# Tableau Palette
# ---------------
plot_colortable(mcolors.TABLEAU_COLORS, ncols=2, sort_colors=False)
# %%
# ----------
# CSS Colors
# ----------
# sphinx_gallery_thumbnail_number = 3
plot_colortable(mcolors.CSS4_COLORS)
plt.show()
# %%
# -----------
# XKCD Colors
# -----------
# Matplotlib supports colors from the
# `xkcd color survey <https://xkcd.com/color/rgb/>`_, e.g. ``"xkcd:sky blue"``. Since
# this contains almost 1000 colors, a figure of this would be very large and is thus
# omitted here. You can use the following code to generate the overview yourself ::
#
# xkcd_fig = plot_colortable(mcolors.XKCD_COLORS)
# xkcd_fig.savefig("XKCD_Colors.png")
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.colors.rgb_to_hsv`
# - `matplotlib.colors.to_rgba`
# - `matplotlib.figure.Figure.get_size_inches`
# - `matplotlib.figure.Figure.subplots_adjust`
# - `matplotlib.axes.Axes.text`
# - `matplotlib.patches.Rectangle`
#
# .. tags::
#
# styling: color
# purpose: reference
| stable__gallery__color__named_colors | 1 | figure_001.png | List of named colors — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/named_colors.html#xkcd-colors | https://matplotlib.org/stable/_downloads/861cf0b07b083f3c44ddd625a0e99000/named_colors.py | named_colors.py | color | ok | 3 | null | |
"""
====================
List of named colors
====================
This plots a list of the named colors supported by Matplotlib.
For more information on colors in matplotlib see
* the :ref:`colors_def` tutorial;
* the `matplotlib.colors` API;
* the :doc:`/gallery/color/color_demo`.
----------------------------
Helper Function for Plotting
----------------------------
First we define a helper function for making a table of colors, then we use it
on some common color categories.
"""
import math
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Rectangle
def plot_colortable(colors, *, ncols=4, sort_colors=True):
cell_width = 212
cell_height = 22
swatch_width = 48
margin = 12
# Sort colors by hue, saturation, value and name.
if sort_colors is True:
names = sorted(
colors, key=lambda c: tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(c))))
else:
names = list(colors)
n = len(names)
nrows = math.ceil(n / ncols)
width = cell_width * ncols + 2 * margin
height = cell_height * nrows + 2 * margin
dpi = 72
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
fig.subplots_adjust(margin/width, margin/height,
(width-margin)/width, (height-margin)/height)
ax.set_xlim(0, cell_width * ncols)
ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
ax.yaxis.set_visible(False)
ax.xaxis.set_visible(False)
ax.set_axis_off()
for i, name in enumerate(names):
row = i % nrows
col = i // nrows
y = row * cell_height
swatch_start_x = cell_width * col
text_pos_x = cell_width * col + swatch_width + 7
ax.text(text_pos_x, y, name, fontsize=14,
horizontalalignment='left',
verticalalignment='center')
ax.add_patch(
Rectangle(xy=(swatch_start_x, y-9), width=swatch_width,
height=18, facecolor=colors[name], edgecolor='0.7')
)
return fig
# %%
# -----------
# Base colors
# -----------
plot_colortable(mcolors.BASE_COLORS, ncols=3, sort_colors=False)
# %%
# ---------------
# Tableau Palette
# ---------------
plot_colortable(mcolors.TABLEAU_COLORS, ncols=2, sort_colors=False)
# %%
# ----------
# CSS Colors
# ----------
# sphinx_gallery_thumbnail_number = 3
plot_colortable(mcolors.CSS4_COLORS)
plt.show()
# %%
# -----------
# XKCD Colors
# -----------
# Matplotlib supports colors from the
# `xkcd color survey <https://xkcd.com/color/rgb/>`_, e.g. ``"xkcd:sky blue"``. Since
# this contains almost 1000 colors, a figure of this would be very large and is thus
# omitted here. You can use the following code to generate the overview yourself ::
#
# xkcd_fig = plot_colortable(mcolors.XKCD_COLORS)
# xkcd_fig.savefig("XKCD_Colors.png")
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.colors`
# - `matplotlib.colors.rgb_to_hsv`
# - `matplotlib.colors.to_rgba`
# - `matplotlib.figure.Figure.get_size_inches`
# - `matplotlib.figure.Figure.subplots_adjust`
# - `matplotlib.axes.Axes.text`
# - `matplotlib.patches.Rectangle`
#
# .. tags::
#
# styling: color
# purpose: reference
| stable__gallery__color__named_colors | 2 | figure_002.png | List of named colors — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/named_colors.html#xkcd-colors | https://matplotlib.org/stable/_downloads/861cf0b07b083f3c44ddd625a0e99000/named_colors.py | named_colors.py | color | ok | 3 | null | |
"""
=================================
Ways to set a color's alpha value
=================================
Compare setting alpha by the *alpha* keyword argument and by one of the Matplotlib color
formats. Often, the *alpha* keyword is the only tool needed to add transparency to a
color. In some cases, the *(matplotlib_color, alpha)* color format provides an easy way
to fine-tune the appearance of a Figure.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility.
np.random.seed(19680801)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4))
x_values = [n for n in range(20)]
y_values = np.random.randn(20)
facecolors = ['green' if y > 0 else 'red' for y in y_values]
edgecolors = facecolors
ax1.bar(x_values, y_values, color=facecolors, edgecolor=edgecolors, alpha=0.5)
ax1.set_title("Explicit 'alpha' keyword value\nshared by all bars and edges")
# Normalize y values to get distinct face alpha values.
abs_y = [abs(y) for y in y_values]
face_alphas = [n / max(abs_y) for n in abs_y]
edge_alphas = [1 - alpha for alpha in face_alphas]
colors_with_alphas = list(zip(facecolors, face_alphas))
edgecolors_with_alphas = list(zip(edgecolors, edge_alphas))
ax2.bar(x_values, y_values, color=colors_with_alphas,
edgecolor=edgecolors_with_alphas)
ax2.set_title('Normalized alphas for\neach bar and each edge')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.bar`
# - `matplotlib.pyplot.subplots`
#
# .. tags::
#
# styling: color
# plot-type: bar
# level: beginner
| stable__gallery__color__set_alpha | 0 | figure_000.png | Ways to set a color's alpha value — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/color/set_alpha.html#ways-to-set-a-color-s-alpha-value | https://matplotlib.org/stable/_downloads/8ac9df75950acff1ebf040a1d2761824/set_alpha.py | set_alpha.py | color | ok | 1 | null | |
"""
===========
Close event
===========
Example to show connecting events that occur when the figure closes.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
def on_close(event):
print('Closed Figure!')
fig = plt.figure()
fig.canvas.mpl_connect('close_event', on_close)
plt.text(0.35, 0.5, 'Close Me!', dict(size=30))
plt.show()
| stable__gallery__event_handling__close_event | 0 | figure_000.png | Close event — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/close_event.html#sphx-glr-download-gallery-event-handling-close-event-py | https://matplotlib.org/stable/_downloads/2488fa170f211c6d0f8dabb214010122/close_event.py | close_event.py | event_handling | ok | 1 | null | |
"""
===========================
Mouse move and click events
===========================
An example of how to interact with the plotting canvas by connecting to move
and click events.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backend_bases import MouseButton
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
def on_move(event):
if event.inaxes:
print(f'data coords {event.xdata} {event.ydata},',
f'pixel coords {event.x} {event.y}')
def on_click(event):
if event.button is MouseButton.LEFT:
print('disconnecting callback')
plt.disconnect(binding_id)
binding_id = plt.connect('motion_notify_event', on_move)
plt.connect('button_press_event', on_click)
plt.show()
| stable__gallery__event_handling__coords_demo | 0 | figure_000.png | Mouse move and click events — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/coords_demo.html#sphx-glr-download-gallery-event-handling-coords-demo-py | https://matplotlib.org/stable/_downloads/4153d91592ea2c87ab46a3a29e0530ed/coords_demo.py | coords_demo.py | event_handling | ok | 1 | null | |
"""
=================
Cross-hair cursor
=================
This example adds a cross-hair as a data cursor. The cross-hair is
implemented as regular line objects that are updated on mouse move.
We show three implementations:
1) A simple cursor implementation that redraws the figure on every mouse move.
This is a bit slow, and you may notice some lag of the cross-hair movement.
2) A cursor that uses blitting for speedup of the rendering.
3) A cursor that snaps to data points.
Faster cursoring is possible using native GUI drawing, as in
:doc:`/gallery/user_interfaces/wxcursor_demo_sgskip`.
The mpldatacursor__ and mplcursors__ third-party packages can be used to
achieve a similar effect.
__ https://github.com/joferkington/mpldatacursor
__ https://github.com/anntzer/mplcursors
.. redirect-from:: /gallery/misc/cursor_demo
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backend_bases import MouseEvent
class Cursor:
"""
A cross hair cursor.
"""
def __init__(self, ax):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
# text location in axes coordinates
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def on_mouse_move(self, event):
if not event.inaxes:
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.draw()
else:
self.set_cross_hair_visible(True)
x, y = event.xdata, event.ydata
# update the line positions
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.draw()
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Simple cursor')
ax.plot(x, y, 'o')
cursor = Cursor(ax)
fig.canvas.mpl_connect('motion_notify_event', cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
# %%
# Faster redrawing using blitting
# """""""""""""""""""""""""""""""
# This technique stores the rendered plot as a background image. Only the
# changed artists (cross-hair lines and text) are rendered anew. They are
# combined with the background using blitting.
#
# This technique is significantly faster. It requires a bit more setup because
# the background has to be stored without the cross-hair lines (see
# ``create_new_background()``). Additionally, a new background has to be
# created whenever the figure changes. This is achieved by connecting to the
# ``'draw_event'``.
class BlittedCursor:
"""
A cross-hair cursor using blitting for faster redraw.
"""
def __init__(self, ax):
self.ax = ax
self.background = None
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
# text location in axes coordinates
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
self._creating_background = False
ax.figure.canvas.mpl_connect('draw_event', self.on_draw)
def on_draw(self, event):
self.create_new_background()
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def create_new_background(self):
if self._creating_background:
# discard calls triggered from within this function
return
self._creating_background = True
self.set_cross_hair_visible(False)
self.ax.figure.canvas.draw()
self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.bbox)
self.set_cross_hair_visible(True)
self._creating_background = False
def on_mouse_move(self, event):
if self.background is None:
self.create_new_background()
if not event.inaxes:
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.restore_region(self.background)
self.ax.figure.canvas.blit(self.ax.bbox)
else:
self.set_cross_hair_visible(True)
# update the line positions
x, y = event.xdata, event.ydata
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.restore_region(self.background)
self.ax.draw_artist(self.horizontal_line)
self.ax.draw_artist(self.vertical_line)
self.ax.draw_artist(self.text)
self.ax.figure.canvas.blit(self.ax.bbox)
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Blitted cursor')
ax.plot(x, y, 'o')
blitted_cursor = BlittedCursor(ax)
fig.canvas.mpl_connect('motion_notify_event', blitted_cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
# %%
# Snapping to data points
# """""""""""""""""""""""
# The following cursor snaps its position to the data points of a `.Line2D`
# object.
#
# To save unnecessary redraws, the index of the last indicated data point is
# saved in ``self._last_index``. A redraw is only triggered when the mouse
# moves far enough so that another data point must be selected. This reduces
# the lag due to many redraws. Of course, blitting could still be added on top
# for additional speedup.
class SnappingCursor:
"""
A cross-hair cursor that snaps to the data point of a line, which is
closest to the *x* position of the cursor.
For simplicity, this assumes that *x* values of the data are sorted.
"""
def __init__(self, ax, line):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
self.x, self.y = line.get_data()
self._last_index = None
# text location in axes coords
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def on_mouse_move(self, event):
if not event.inaxes:
self._last_index = None
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.draw()
else:
self.set_cross_hair_visible(True)
x, y = event.xdata, event.ydata
index = min(np.searchsorted(self.x, x), len(self.x) - 1)
if index == self._last_index:
return # still on the same data point. Nothing to do.
self._last_index = index
x = self.x[index]
y = self.y[index]
# update the line positions
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.draw()
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Snapping cursor')
line, = ax.plot(x, y, 'o')
snap_cursor = SnappingCursor(ax, line)
fig.canvas.mpl_connect('motion_notify_event', snap_cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
plt.show()
| stable__gallery__event_handling__cursor_demo | 0 | figure_000.png | Cross-hair cursor — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/cursor_demo.html#sphx-glr-download-gallery-event-handling-cursor-demo-py | https://matplotlib.org/stable/_downloads/b50d37f9b82e9455a7917dd5929c697f/cursor_demo.py | cursor_demo.py | event_handling | ok | 3 | null | |
"""
=================
Cross-hair cursor
=================
This example adds a cross-hair as a data cursor. The cross-hair is
implemented as regular line objects that are updated on mouse move.
We show three implementations:
1) A simple cursor implementation that redraws the figure on every mouse move.
This is a bit slow, and you may notice some lag of the cross-hair movement.
2) A cursor that uses blitting for speedup of the rendering.
3) A cursor that snaps to data points.
Faster cursoring is possible using native GUI drawing, as in
:doc:`/gallery/user_interfaces/wxcursor_demo_sgskip`.
The mpldatacursor__ and mplcursors__ third-party packages can be used to
achieve a similar effect.
__ https://github.com/joferkington/mpldatacursor
__ https://github.com/anntzer/mplcursors
.. redirect-from:: /gallery/misc/cursor_demo
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backend_bases import MouseEvent
class Cursor:
"""
A cross hair cursor.
"""
def __init__(self, ax):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
# text location in axes coordinates
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def on_mouse_move(self, event):
if not event.inaxes:
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.draw()
else:
self.set_cross_hair_visible(True)
x, y = event.xdata, event.ydata
# update the line positions
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.draw()
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Simple cursor')
ax.plot(x, y, 'o')
cursor = Cursor(ax)
fig.canvas.mpl_connect('motion_notify_event', cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
# %%
# Faster redrawing using blitting
# """""""""""""""""""""""""""""""
# This technique stores the rendered plot as a background image. Only the
# changed artists (cross-hair lines and text) are rendered anew. They are
# combined with the background using blitting.
#
# This technique is significantly faster. It requires a bit more setup because
# the background has to be stored without the cross-hair lines (see
# ``create_new_background()``). Additionally, a new background has to be
# created whenever the figure changes. This is achieved by connecting to the
# ``'draw_event'``.
class BlittedCursor:
"""
A cross-hair cursor using blitting for faster redraw.
"""
def __init__(self, ax):
self.ax = ax
self.background = None
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
# text location in axes coordinates
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
self._creating_background = False
ax.figure.canvas.mpl_connect('draw_event', self.on_draw)
def on_draw(self, event):
self.create_new_background()
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def create_new_background(self):
if self._creating_background:
# discard calls triggered from within this function
return
self._creating_background = True
self.set_cross_hair_visible(False)
self.ax.figure.canvas.draw()
self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.bbox)
self.set_cross_hair_visible(True)
self._creating_background = False
def on_mouse_move(self, event):
if self.background is None:
self.create_new_background()
if not event.inaxes:
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.restore_region(self.background)
self.ax.figure.canvas.blit(self.ax.bbox)
else:
self.set_cross_hair_visible(True)
# update the line positions
x, y = event.xdata, event.ydata
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.restore_region(self.background)
self.ax.draw_artist(self.horizontal_line)
self.ax.draw_artist(self.vertical_line)
self.ax.draw_artist(self.text)
self.ax.figure.canvas.blit(self.ax.bbox)
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Blitted cursor')
ax.plot(x, y, 'o')
blitted_cursor = BlittedCursor(ax)
fig.canvas.mpl_connect('motion_notify_event', blitted_cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
# %%
# Snapping to data points
# """""""""""""""""""""""
# The following cursor snaps its position to the data points of a `.Line2D`
# object.
#
# To save unnecessary redraws, the index of the last indicated data point is
# saved in ``self._last_index``. A redraw is only triggered when the mouse
# moves far enough so that another data point must be selected. This reduces
# the lag due to many redraws. Of course, blitting could still be added on top
# for additional speedup.
class SnappingCursor:
"""
A cross-hair cursor that snaps to the data point of a line, which is
closest to the *x* position of the cursor.
For simplicity, this assumes that *x* values of the data are sorted.
"""
def __init__(self, ax, line):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
self.x, self.y = line.get_data()
self._last_index = None
# text location in axes coords
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def on_mouse_move(self, event):
if not event.inaxes:
self._last_index = None
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.draw()
else:
self.set_cross_hair_visible(True)
x, y = event.xdata, event.ydata
index = min(np.searchsorted(self.x, x), len(self.x) - 1)
if index == self._last_index:
return # still on the same data point. Nothing to do.
self._last_index = index
x = self.x[index]
y = self.y[index]
# update the line positions
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.draw()
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Snapping cursor')
line, = ax.plot(x, y, 'o')
snap_cursor = SnappingCursor(ax, line)
fig.canvas.mpl_connect('motion_notify_event', snap_cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
plt.show()
| stable__gallery__event_handling__cursor_demo | 1 | figure_001.png | Cross-hair cursor — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/cursor_demo.html#sphx-glr-download-gallery-event-handling-cursor-demo-py | https://matplotlib.org/stable/_downloads/b50d37f9b82e9455a7917dd5929c697f/cursor_demo.py | cursor_demo.py | event_handling | ok | 3 | null | |
"""
=================
Cross-hair cursor
=================
This example adds a cross-hair as a data cursor. The cross-hair is
implemented as regular line objects that are updated on mouse move.
We show three implementations:
1) A simple cursor implementation that redraws the figure on every mouse move.
This is a bit slow, and you may notice some lag of the cross-hair movement.
2) A cursor that uses blitting for speedup of the rendering.
3) A cursor that snaps to data points.
Faster cursoring is possible using native GUI drawing, as in
:doc:`/gallery/user_interfaces/wxcursor_demo_sgskip`.
The mpldatacursor__ and mplcursors__ third-party packages can be used to
achieve a similar effect.
__ https://github.com/joferkington/mpldatacursor
__ https://github.com/anntzer/mplcursors
.. redirect-from:: /gallery/misc/cursor_demo
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backend_bases import MouseEvent
class Cursor:
"""
A cross hair cursor.
"""
def __init__(self, ax):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
# text location in axes coordinates
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def on_mouse_move(self, event):
if not event.inaxes:
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.draw()
else:
self.set_cross_hair_visible(True)
x, y = event.xdata, event.ydata
# update the line positions
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.draw()
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Simple cursor')
ax.plot(x, y, 'o')
cursor = Cursor(ax)
fig.canvas.mpl_connect('motion_notify_event', cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
# %%
# Faster redrawing using blitting
# """""""""""""""""""""""""""""""
# This technique stores the rendered plot as a background image. Only the
# changed artists (cross-hair lines and text) are rendered anew. They are
# combined with the background using blitting.
#
# This technique is significantly faster. It requires a bit more setup because
# the background has to be stored without the cross-hair lines (see
# ``create_new_background()``). Additionally, a new background has to be
# created whenever the figure changes. This is achieved by connecting to the
# ``'draw_event'``.
class BlittedCursor:
"""
A cross-hair cursor using blitting for faster redraw.
"""
def __init__(self, ax):
self.ax = ax
self.background = None
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
# text location in axes coordinates
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
self._creating_background = False
ax.figure.canvas.mpl_connect('draw_event', self.on_draw)
def on_draw(self, event):
self.create_new_background()
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def create_new_background(self):
if self._creating_background:
# discard calls triggered from within this function
return
self._creating_background = True
self.set_cross_hair_visible(False)
self.ax.figure.canvas.draw()
self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.bbox)
self.set_cross_hair_visible(True)
self._creating_background = False
def on_mouse_move(self, event):
if self.background is None:
self.create_new_background()
if not event.inaxes:
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.restore_region(self.background)
self.ax.figure.canvas.blit(self.ax.bbox)
else:
self.set_cross_hair_visible(True)
# update the line positions
x, y = event.xdata, event.ydata
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.restore_region(self.background)
self.ax.draw_artist(self.horizontal_line)
self.ax.draw_artist(self.vertical_line)
self.ax.draw_artist(self.text)
self.ax.figure.canvas.blit(self.ax.bbox)
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Blitted cursor')
ax.plot(x, y, 'o')
blitted_cursor = BlittedCursor(ax)
fig.canvas.mpl_connect('motion_notify_event', blitted_cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
# %%
# Snapping to data points
# """""""""""""""""""""""
# The following cursor snaps its position to the data points of a `.Line2D`
# object.
#
# To save unnecessary redraws, the index of the last indicated data point is
# saved in ``self._last_index``. A redraw is only triggered when the mouse
# moves far enough so that another data point must be selected. This reduces
# the lag due to many redraws. Of course, blitting could still be added on top
# for additional speedup.
class SnappingCursor:
"""
A cross-hair cursor that snaps to the data point of a line, which is
closest to the *x* position of the cursor.
For simplicity, this assumes that *x* values of the data are sorted.
"""
def __init__(self, ax, line):
self.ax = ax
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
self.x, self.y = line.get_data()
self._last_index = None
# text location in axes coords
self.text = ax.text(0.72, 0.9, '', transform=ax.transAxes)
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def on_mouse_move(self, event):
if not event.inaxes:
self._last_index = None
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.draw()
else:
self.set_cross_hair_visible(True)
x, y = event.xdata, event.ydata
index = min(np.searchsorted(self.x, x), len(self.x) - 1)
if index == self._last_index:
return # still on the same data point. Nothing to do.
self._last_index = index
x = self.x[index]
y = self.y[index]
# update the line positions
self.horizontal_line.set_ydata([y])
self.vertical_line.set_xdata([x])
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
self.ax.figure.canvas.draw()
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Snapping cursor')
line, = ax.plot(x, y, 'o')
snap_cursor = SnappingCursor(ax, line)
fig.canvas.mpl_connect('motion_notify_event', snap_cursor.on_mouse_move)
# Simulate a mouse move to (0.5, 0.5), needed for online docs
t = ax.transData
MouseEvent(
"motion_notify_event", ax.figure.canvas, *t.transform((0.5, 0.5))
)._process()
plt.show()
| stable__gallery__event_handling__cursor_demo | 2 | figure_002.png | Cross-hair cursor — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/cursor_demo.html#sphx-glr-download-gallery-event-handling-cursor-demo-py | https://matplotlib.org/stable/_downloads/b50d37f9b82e9455a7917dd5929c697f/cursor_demo.py | cursor_demo.py | event_handling | ok | 3 | null | |
"""
============
Data browser
============
Connecting data between multiple canvases.
This example covers how to interact data with multiple canvases. This
lets you select and highlight a point on one axis, and generating the
data of that point on the other axis.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import numpy as np
class PointBrowser:
"""
Click on a point to select and highlight it -- the data that
generated the point will be shown in the lower Axes. Use the 'n'
and 'p' keys to browse through the next and previous points
"""
def __init__(self):
self.lastind = 0
self.text = ax.text(0.05, 0.95, 'selected: none',
transform=ax.transAxes, va='top')
self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4,
color='yellow', visible=False)
def on_press(self, event):
if self.lastind is None:
return
if event.key not in ('n', 'p'):
return
if event.key == 'n':
inc = 1
else:
inc = -1
self.lastind += inc
self.lastind = np.clip(self.lastind, 0, len(xs) - 1)
self.update()
def on_pick(self, event):
if event.artist != line:
return True
N = len(event.ind)
if not N:
return True
# the click locations
x = event.mouseevent.xdata
y = event.mouseevent.ydata
distances = np.hypot(x - xs[event.ind], y - ys[event.ind])
indmin = distances.argmin()
dataind = event.ind[indmin]
self.lastind = dataind
self.update()
def update(self):
if self.lastind is None:
return
dataind = self.lastind
ax2.clear()
ax2.plot(X[dataind])
ax2.text(0.05, 0.9, f'mu={xs[dataind]:1.3f}\nsigma={ys[dataind]:1.3f}',
transform=ax2.transAxes, va='top')
ax2.set_ylim(-0.5, 1.5)
self.selected.set_visible(True)
self.selected.set_data([xs[dataind]], [ys[dataind]])
self.text.set_text('selected: %d' % dataind)
fig.canvas.draw()
if __name__ == '__main__':
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
X = np.random.rand(100, 200)
xs = np.mean(X, axis=1)
ys = np.std(X, axis=1)
fig, (ax, ax2) = plt.subplots(2, 1)
ax.set_title('click on point to plot time series')
line, = ax.plot(xs, ys, 'o', picker=True, pickradius=5)
browser = PointBrowser()
fig.canvas.mpl_connect('pick_event', browser.on_pick)
fig.canvas.mpl_connect('key_press_event', browser.on_press)
plt.show()
| stable__gallery__event_handling__data_browser | 0 | figure_000.png | Data browser — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/data_browser.html#sphx-glr-download-gallery-event-handling-data-browser-py | https://matplotlib.org/stable/_downloads/757512fe68953f07685f6592c084829f/data_browser.py | data_browser.py | event_handling | ok | 1 | null | |
"""
==================================
Figure/Axes enter and leave events
==================================
Illustrate the figure and Axes enter and leave events by changing the
frame colors on enter and leave.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
def on_enter_axes(event):
print('enter_axes', event.inaxes)
event.inaxes.patch.set_facecolor('yellow')
event.canvas.draw()
def on_leave_axes(event):
print('leave_axes', event.inaxes)
event.inaxes.patch.set_facecolor('white')
event.canvas.draw()
def on_enter_figure(event):
print('enter_figure', event.canvas.figure)
event.canvas.figure.patch.set_facecolor('red')
event.canvas.draw()
def on_leave_figure(event):
print('leave_figure', event.canvas.figure)
event.canvas.figure.patch.set_facecolor('grey')
event.canvas.draw()
fig, axs = plt.subplots(2, 1)
fig.suptitle('mouse hover over figure or Axes to trigger events')
fig.canvas.mpl_connect('figure_enter_event', on_enter_figure)
fig.canvas.mpl_connect('figure_leave_event', on_leave_figure)
fig.canvas.mpl_connect('axes_enter_event', on_enter_axes)
fig.canvas.mpl_connect('axes_leave_event', on_leave_axes)
plt.show()
| stable__gallery__event_handling__figure_axes_enter_leave | 0 | figure_000.png | Figure/Axes enter and leave events — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/figure_axes_enter_leave.html#sphx-glr-download-gallery-event-handling-figure-axes-enter-leave-py | https://matplotlib.org/stable/_downloads/6610549796b7ae801a732cb47e54fea6/figure_axes_enter_leave.py | figure_axes_enter_leave.py | event_handling | ok | 1 | null | |
"""
============
Scroll event
============
In this example a scroll wheel event is used to scroll through 2D slices of
3D data.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
class IndexTracker:
def __init__(self, ax, X):
self.index = 0
self.X = X
self.ax = ax
self.im = ax.imshow(self.X[:, :, self.index])
self.update()
def on_scroll(self, event):
print(event.button, event.step)
increment = 1 if event.button == 'up' else -1
max_index = self.X.shape[-1] - 1
self.index = np.clip(self.index + increment, 0, max_index)
self.update()
def update(self):
self.im.set_data(self.X[:, :, self.index])
self.ax.set_title(
f'Use scroll wheel to navigate\nindex {self.index}')
self.im.axes.figure.canvas.draw()
x, y, z = np.ogrid[-10:10:100j, -10:10:100j, 1:10:20j]
X = np.sin(x * y * z) / (x * y * z)
fig, ax = plt.subplots()
# create an IndexTracker and make sure it lives during the whole
# lifetime of the figure by assigning it to a variable
tracker = IndexTracker(ax, X)
fig.canvas.mpl_connect('scroll_event', tracker.on_scroll)
plt.show()
| stable__gallery__event_handling__image_slices_viewer | 0 | figure_000.png | Scroll event — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/image_slices_viewer.html#sphx-glr-download-gallery-event-handling-image-slices-viewer-py | https://matplotlib.org/stable/_downloads/c56b886d4ce4555a31768b6d5e456be0/image_slices_viewer.py | image_slices_viewer.py | event_handling | ok | 1 | null | |
"""
==============
Keypress event
==============
Show how to connect to keypress events.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import sys
import matplotlib.pyplot as plt
import numpy as np
def on_press(event):
print('press', event.key)
sys.stdout.flush()
if event.key == 'x':
visible = xl.get_visible()
xl.set_visible(not visible)
fig.canvas.draw()
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', on_press)
ax.plot(np.random.rand(12), np.random.rand(12), 'go')
xl = ax.set_xlabel('easy come, easy go')
ax.set_title('Press a key')
plt.show()
| stable__gallery__event_handling__keypress_demo | 0 | figure_000.png | Keypress event — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/keypress_demo.html#sphx-glr-download-gallery-event-handling-keypress-demo-py | https://matplotlib.org/stable/_downloads/423cb6ca263e891b16291fc415c9f7f0/keypress_demo.py | keypress_demo.py | event_handling | ok | 1 | null | |
"""
==========
Lasso Demo
==========
Use a lasso to select a set of points and get the indices of the selected points.
A callback is used to change the color of the selected points.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors as mcolors
from matplotlib import path
from matplotlib.collections import RegularPolyCollection
from matplotlib.widgets import Lasso
class LassoManager:
def __init__(self, ax, data):
# The information of whether a point has been selected or not is stored in the
# collection's array (0 = out, 1 = in), which then gets colormapped to blue
# (out) and red (in).
self.collection = RegularPolyCollection(
6, sizes=(100,), offset_transform=ax.transData,
offsets=data, array=np.zeros(len(data)),
clim=(0, 1), cmap=mcolors.ListedColormap(["tab:blue", "tab:red"]))
ax.add_collection(self.collection)
canvas = ax.figure.canvas
canvas.mpl_connect('button_press_event', self.on_press)
canvas.mpl_connect('button_release_event', self.on_release)
def callback(self, verts):
data = self.collection.get_offsets()
self.collection.set_array(path.Path(verts).contains_points(data))
canvas = self.collection.figure.canvas
canvas.draw_idle()
del self.lasso
def on_press(self, event):
canvas = self.collection.figure.canvas
if event.inaxes is not self.collection.axes or canvas.widgetlock.locked():
return
self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
canvas.widgetlock(self.lasso) # acquire a lock on the widget drawing
def on_release(self, event):
canvas = self.collection.figure.canvas
if hasattr(self, 'lasso') and canvas.widgetlock.isowner(self.lasso):
canvas.widgetlock.release(self.lasso)
if __name__ == '__main__':
np.random.seed(19680801)
ax = plt.figure().add_subplot(
xlim=(0, 1), ylim=(0, 1), title='Lasso points using left mouse button')
manager = LassoManager(ax, np.random.rand(100, 2))
plt.show()
| stable__gallery__event_handling__lasso_demo | 0 | figure_000.png | Lasso Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/lasso_demo.html#sphx-glr-download-gallery-event-handling-lasso-demo-py | https://matplotlib.org/stable/_downloads/a6cb4df0e5baf29165f46c7de8319b87/lasso_demo.py | lasso_demo.py | event_handling | ok | 1 | null | |
"""
==============
Legend picking
==============
Enable picking on the legend to toggle the original line on and off
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 1)
y1 = 2 * np.sin(2 * np.pi * t)
y2 = 4 * np.sin(2 * np.pi * 2 * t)
fig, ax = plt.subplots()
ax.set_title('Click on legend line to toggle line on/off')
(line1, ) = ax.plot(t, y1, lw=2, label='1 Hz')
(line2, ) = ax.plot(t, y2, lw=2, label='2 Hz')
leg = ax.legend(fancybox=True, shadow=True)
lines = [line1, line2]
map_legend_to_ax = {} # Will map legend lines to original lines.
pickradius = 5 # Points (Pt). How close the click needs to be to trigger an event.
for legend_line, ax_line in zip(leg.get_lines(), lines):
legend_line.set_picker(pickradius) # Enable picking on the legend line.
map_legend_to_ax[legend_line] = ax_line
def on_pick(event):
# On the pick event, find the original line corresponding to the legend
# proxy line, and toggle its visibility.
legend_line = event.artist
# Do nothing if the source of the event is not a legend line.
if legend_line not in map_legend_to_ax:
return
ax_line = map_legend_to_ax[legend_line]
visible = not ax_line.get_visible()
ax_line.set_visible(visible)
# Change the alpha on the line in the legend, so we can see what lines
# have been toggled.
legend_line.set_alpha(1.0 if visible else 0.2)
fig.canvas.draw()
fig.canvas.mpl_connect('pick_event', on_pick)
# Works even if the legend is draggable. This is independent from picking legend lines.
leg.set_draggable(True)
plt.show()
| stable__gallery__event_handling__legend_picking | 0 | figure_000.png | Legend picking — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/legend_picking.html#sphx-glr-download-gallery-event-handling-legend-picking-py | https://matplotlib.org/stable/_downloads/cf600c14334c7d04e8a2ef88c02c9d7c/legend_picking.py | legend_picking.py | event_handling | ok | 1 | null | |
"""
=============
Looking glass
=============
Example using mouse events to simulate a looking glass for inspecting data.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
# Fixing random state for reproducibility
np.random.seed(19680801)
x, y = np.random.rand(2, 200)
fig, ax = plt.subplots()
circ = patches.Circle((0.5, 0.5), 0.25, alpha=0.8, fc='yellow')
ax.add_patch(circ)
ax.plot(x, y, alpha=0.2)
line, = ax.plot(x, y, alpha=1.0, clip_path=circ)
ax.set_title("Left click and drag to move looking glass")
class EventHandler:
def __init__(self):
fig.canvas.mpl_connect('button_press_event', self.on_press)
fig.canvas.mpl_connect('button_release_event', self.on_release)
fig.canvas.mpl_connect('motion_notify_event', self.on_move)
self.x0, self.y0 = circ.center
self.pressevent = None
def on_press(self, event):
if event.inaxes != ax:
return
if not circ.contains(event)[0]:
return
self.pressevent = event
def on_release(self, event):
self.pressevent = None
self.x0, self.y0 = circ.center
def on_move(self, event):
if self.pressevent is None or event.inaxes != self.pressevent.inaxes:
return
dx = event.xdata - self.pressevent.xdata
dy = event.ydata - self.pressevent.ydata
circ.center = self.x0 + dx, self.y0 + dy
line.set_clip_path(circ)
fig.canvas.draw()
handler = EventHandler()
plt.show()
| stable__gallery__event_handling__looking_glass | 0 | figure_000.png | Looking glass — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/looking_glass.html#sphx-glr-download-gallery-event-handling-looking-glass-py | https://matplotlib.org/stable/_downloads/3f1ecbb039cffe24c51d1499214bb495/looking_glass.py | looking_glass.py | event_handling | ok | 1 | null | |
"""
===========
Path editor
===========
Sharing events across GUIs.
This example demonstrates a cross-GUI application using Matplotlib event
handling to interact with and modify objects on the canvas.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backend_bases import MouseButton
from matplotlib.patches import PathPatch
from matplotlib.path import Path
fig, ax = plt.subplots()
pathdata = [
(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(*pathdata)
path = Path(verts, codes)
patch = PathPatch(
path, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
class PathInteractor:
"""
A path editor.
Press 't' to toggle vertex markers on and off. When vertex markers are on,
they can be dragged with the mouse.
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, pathpatch):
self.ax = pathpatch.axes
canvas = self.ax.figure.canvas
self.pathpatch = pathpatch
self.pathpatch.set_animated(True)
x, y = zip(*self.pathpatch.get_path().vertices)
self.line, = ax.plot(
x, y, marker='o', markerfacecolor='r', animated=True)
self._ind = None # the active vertex
canvas.mpl_connect('draw_event', self.on_draw)
canvas.mpl_connect('button_press_event', self.on_button_press)
canvas.mpl_connect('key_press_event', self.on_key_press)
canvas.mpl_connect('button_release_event', self.on_button_release)
canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas = canvas
def get_ind_under_point(self, event):
"""
Return the index of the point closest to the event position or *None*
if no point is within ``self.epsilon`` to the event position.
"""
xy = self.pathpatch.get_path().vertices
xyt = self.pathpatch.get_transform().transform(xy) # to display coords
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
ind = d.argmin()
return ind if d[ind] < self.epsilon else None
def on_draw(self, event):
"""Callback for draws."""
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.pathpatch)
self.ax.draw_artist(self.line)
def on_button_press(self, event):
"""Callback for mouse button presses."""
if (event.inaxes is None
or event.button != MouseButton.LEFT
or not self.showverts):
return
self._ind = self.get_ind_under_point(event)
def on_button_release(self, event):
"""Callback for mouse button releases."""
if (event.button != MouseButton.LEFT
or not self.showverts):
return
self._ind = None
def on_key_press(self, event):
"""Callback for key presses."""
if not event.inaxes:
return
if event.key == 't':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
self.canvas.draw()
def on_mouse_move(self, event):
"""Callback for mouse movements."""
if (self._ind is None
or event.inaxes is None
or event.button != MouseButton.LEFT
or not self.showverts):
return
vertices = self.pathpatch.get_path().vertices
vertices[self._ind] = event.xdata, event.ydata
self.line.set_data(zip(*vertices))
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.pathpatch)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
interactor = PathInteractor(patch)
ax.set_title('drag vertices to update path')
ax.set_xlim(-3, 4)
ax.set_ylim(-3, 4)
plt.show()
| stable__gallery__event_handling__path_editor | 0 | figure_000.png | Path editor — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/path_editor.html#sphx-glr-download-gallery-event-handling-path-editor-py | https://matplotlib.org/stable/_downloads/2b072ea346f552f1d4e4cab8f3eeef72/path_editor.py | path_editor.py | event_handling | ok | 1 | null | |
"""
===============
Pick event demo
===============
You can enable picking by setting the "picker" property of an artist
(for example, a Matplotlib Line2D, Text, Patch, Polygon, AxesImage,
etc.)
There are a variety of meanings of the picker property:
* *None* - picking is disabled for this artist (default)
* bool - if *True* then picking will be enabled and the artist will fire a pick
event if the mouse event is over the artist.
Setting ``pickradius`` will add an epsilon tolerance in points and the artist
will fire off an event if its data is within epsilon of the mouse event. For
some artists like lines and patch collections, the artist may provide
additional data to the pick event that is generated, for example, the indices
of the data within epsilon of the pick event
* function - if picker is callable, it is a user supplied function which
determines whether the artist is hit by the mouse event. ::
hit, props = picker(artist, mouseevent)
to determine the hit test. If the mouse event is over the artist, return
hit=True and props is a dictionary of properties you want added to the
PickEvent attributes.
After you have enabled an artist for picking by setting the "picker"
property, you need to connect to the figure canvas pick_event to get
pick callbacks on mouse press events. For example, ::
def pick_handler(event):
mouseevent = event.mouseevent
artist = event.artist
# now do something with this...
The pick event (matplotlib.backend_bases.PickEvent) which is passed to
your callback is always fired with two attributes:
mouseevent
the mouse event that generate the pick event.
The mouse event in turn has attributes like x and y (the coordinates in
display space, such as pixels from left, bottom) and xdata, ydata (the
coords in data space). Additionally, you can get information about
which buttons were pressed, which keys were pressed, which Axes
the mouse is over, etc. See matplotlib.backend_bases.MouseEvent
for details.
artist
the matplotlib.artist that generated the pick event.
Additionally, certain artists like Line2D and PatchCollection may
attach additional metadata like the indices into the data that meet
the picker criteria (for example, all the points in the line that are within
the specified epsilon tolerance)
The examples below illustrate each of these methods.
.. note::
These examples exercises the interactive capabilities of Matplotlib, and
this will not appear in the static documentation. Please run this code on
your machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
from matplotlib.image import AxesImage
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text
# Fixing random state for reproducibility
np.random.seed(19680801)
# %%
# Simple picking, lines, rectangles and text
# ------------------------------------------
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.set_title('click on points, rectangles or text', picker=True)
ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red'))
line, = ax1.plot(rand(100), 'o', picker=True, pickradius=5)
# Pick the rectangle.
ax2.bar(range(10), rand(10), picker=True)
for label in ax2.get_xticklabels(): # Make the xtick labels pickable.
label.set_picker(True)
def onpick1(event):
if isinstance(event.artist, Line2D):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print('onpick1 line:', np.column_stack([xdata[ind], ydata[ind]]))
elif isinstance(event.artist, Rectangle):
patch = event.artist
print('onpick1 patch:', patch.get_path())
elif isinstance(event.artist, Text):
text = event.artist
print('onpick1 text:', text.get_text())
fig.canvas.mpl_connect('pick_event', onpick1)
# %%
# Picking with a custom hit test function
# ---------------------------------------
# You can define custom pickers by setting picker to a callable function. The
# function has the signature::
#
# hit, props = func(artist, mouseevent)
#
# to determine the hit test. If the mouse event is over the artist, return
# ``hit=True`` and ``props`` is a dictionary of properties you want added to
# the `.PickEvent` attributes.
def line_picker(line, mouseevent):
"""
Find the points within a certain distance from the mouseclick in
data coords and attach some extra attributes, pickx and picky
which are the data points that were picked.
"""
if mouseevent.xdata is None:
return False, dict()
xdata = line.get_xdata()
ydata = line.get_ydata()
maxd = 0.05
d = np.sqrt(
(xdata - mouseevent.xdata)**2 + (ydata - mouseevent.ydata)**2)
ind, = np.nonzero(d <= maxd)
if len(ind):
pickx = xdata[ind]
picky = ydata[ind]
props = dict(ind=ind, pickx=pickx, picky=picky)
return True, props
else:
return False, dict()
def onpick2(event):
print('onpick2 line:', event.pickx, event.picky)
fig, ax = plt.subplots()
ax.set_title('custom picker for line data')
line, = ax.plot(rand(100), rand(100), 'o', picker=line_picker)
fig.canvas.mpl_connect('pick_event', onpick2)
# %%
# Picking on a scatter plot
# -------------------------
# A scatter plot is backed by a `~matplotlib.collections.PathCollection`.
x, y, c, s = rand(4, 100)
def onpick3(event):
ind = event.ind
print('onpick3 scatter:', ind, x[ind], y[ind])
fig, ax = plt.subplots()
ax.scatter(x, y, 100*s, c, picker=True)
fig.canvas.mpl_connect('pick_event', onpick3)
# %%
# Picking images
# --------------
# Images plotted using `.Axes.imshow` are `~matplotlib.image.AxesImage`
# objects.
fig, ax = plt.subplots()
ax.imshow(rand(10, 5), extent=(1, 2, 1, 2), picker=True)
ax.imshow(rand(5, 10), extent=(3, 4, 1, 2), picker=True)
ax.imshow(rand(20, 25), extent=(1, 2, 3, 4), picker=True)
ax.imshow(rand(30, 12), extent=(3, 4, 3, 4), picker=True)
ax.set(xlim=(0, 5), ylim=(0, 5))
def onpick4(event):
artist = event.artist
if isinstance(artist, AxesImage):
im = artist
A = im.get_array()
print('onpick4 image', A.shape)
fig.canvas.mpl_connect('pick_event', onpick4)
plt.show()
| stable__gallery__event_handling__pick_event_demo | 0 | figure_000.png | Pick event demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/pick_event_demo.html#sphx-glr-download-gallery-event-handling-pick-event-demo-py | https://matplotlib.org/stable/_downloads/97bcffbb1f60980e1ed023c1abf6b9f3/pick_event_demo.py | pick_event_demo.py | event_handling | ok | 4 | null | |
"""
===============
Pick event demo
===============
You can enable picking by setting the "picker" property of an artist
(for example, a Matplotlib Line2D, Text, Patch, Polygon, AxesImage,
etc.)
There are a variety of meanings of the picker property:
* *None* - picking is disabled for this artist (default)
* bool - if *True* then picking will be enabled and the artist will fire a pick
event if the mouse event is over the artist.
Setting ``pickradius`` will add an epsilon tolerance in points and the artist
will fire off an event if its data is within epsilon of the mouse event. For
some artists like lines and patch collections, the artist may provide
additional data to the pick event that is generated, for example, the indices
of the data within epsilon of the pick event
* function - if picker is callable, it is a user supplied function which
determines whether the artist is hit by the mouse event. ::
hit, props = picker(artist, mouseevent)
to determine the hit test. If the mouse event is over the artist, return
hit=True and props is a dictionary of properties you want added to the
PickEvent attributes.
After you have enabled an artist for picking by setting the "picker"
property, you need to connect to the figure canvas pick_event to get
pick callbacks on mouse press events. For example, ::
def pick_handler(event):
mouseevent = event.mouseevent
artist = event.artist
# now do something with this...
The pick event (matplotlib.backend_bases.PickEvent) which is passed to
your callback is always fired with two attributes:
mouseevent
the mouse event that generate the pick event.
The mouse event in turn has attributes like x and y (the coordinates in
display space, such as pixels from left, bottom) and xdata, ydata (the
coords in data space). Additionally, you can get information about
which buttons were pressed, which keys were pressed, which Axes
the mouse is over, etc. See matplotlib.backend_bases.MouseEvent
for details.
artist
the matplotlib.artist that generated the pick event.
Additionally, certain artists like Line2D and PatchCollection may
attach additional metadata like the indices into the data that meet
the picker criteria (for example, all the points in the line that are within
the specified epsilon tolerance)
The examples below illustrate each of these methods.
.. note::
These examples exercises the interactive capabilities of Matplotlib, and
this will not appear in the static documentation. Please run this code on
your machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
from matplotlib.image import AxesImage
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text
# Fixing random state for reproducibility
np.random.seed(19680801)
# %%
# Simple picking, lines, rectangles and text
# ------------------------------------------
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.set_title('click on points, rectangles or text', picker=True)
ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red'))
line, = ax1.plot(rand(100), 'o', picker=True, pickradius=5)
# Pick the rectangle.
ax2.bar(range(10), rand(10), picker=True)
for label in ax2.get_xticklabels(): # Make the xtick labels pickable.
label.set_picker(True)
def onpick1(event):
if isinstance(event.artist, Line2D):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print('onpick1 line:', np.column_stack([xdata[ind], ydata[ind]]))
elif isinstance(event.artist, Rectangle):
patch = event.artist
print('onpick1 patch:', patch.get_path())
elif isinstance(event.artist, Text):
text = event.artist
print('onpick1 text:', text.get_text())
fig.canvas.mpl_connect('pick_event', onpick1)
# %%
# Picking with a custom hit test function
# ---------------------------------------
# You can define custom pickers by setting picker to a callable function. The
# function has the signature::
#
# hit, props = func(artist, mouseevent)
#
# to determine the hit test. If the mouse event is over the artist, return
# ``hit=True`` and ``props`` is a dictionary of properties you want added to
# the `.PickEvent` attributes.
def line_picker(line, mouseevent):
"""
Find the points within a certain distance from the mouseclick in
data coords and attach some extra attributes, pickx and picky
which are the data points that were picked.
"""
if mouseevent.xdata is None:
return False, dict()
xdata = line.get_xdata()
ydata = line.get_ydata()
maxd = 0.05
d = np.sqrt(
(xdata - mouseevent.xdata)**2 + (ydata - mouseevent.ydata)**2)
ind, = np.nonzero(d <= maxd)
if len(ind):
pickx = xdata[ind]
picky = ydata[ind]
props = dict(ind=ind, pickx=pickx, picky=picky)
return True, props
else:
return False, dict()
def onpick2(event):
print('onpick2 line:', event.pickx, event.picky)
fig, ax = plt.subplots()
ax.set_title('custom picker for line data')
line, = ax.plot(rand(100), rand(100), 'o', picker=line_picker)
fig.canvas.mpl_connect('pick_event', onpick2)
# %%
# Picking on a scatter plot
# -------------------------
# A scatter plot is backed by a `~matplotlib.collections.PathCollection`.
x, y, c, s = rand(4, 100)
def onpick3(event):
ind = event.ind
print('onpick3 scatter:', ind, x[ind], y[ind])
fig, ax = plt.subplots()
ax.scatter(x, y, 100*s, c, picker=True)
fig.canvas.mpl_connect('pick_event', onpick3)
# %%
# Picking images
# --------------
# Images plotted using `.Axes.imshow` are `~matplotlib.image.AxesImage`
# objects.
fig, ax = plt.subplots()
ax.imshow(rand(10, 5), extent=(1, 2, 1, 2), picker=True)
ax.imshow(rand(5, 10), extent=(3, 4, 1, 2), picker=True)
ax.imshow(rand(20, 25), extent=(1, 2, 3, 4), picker=True)
ax.imshow(rand(30, 12), extent=(3, 4, 3, 4), picker=True)
ax.set(xlim=(0, 5), ylim=(0, 5))
def onpick4(event):
artist = event.artist
if isinstance(artist, AxesImage):
im = artist
A = im.get_array()
print('onpick4 image', A.shape)
fig.canvas.mpl_connect('pick_event', onpick4)
plt.show()
| stable__gallery__event_handling__pick_event_demo | 1 | figure_001.png | Pick event demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/pick_event_demo.html#sphx-glr-download-gallery-event-handling-pick-event-demo-py | https://matplotlib.org/stable/_downloads/97bcffbb1f60980e1ed023c1abf6b9f3/pick_event_demo.py | pick_event_demo.py | event_handling | ok | 4 | null | |
"""
===============
Pick event demo
===============
You can enable picking by setting the "picker" property of an artist
(for example, a Matplotlib Line2D, Text, Patch, Polygon, AxesImage,
etc.)
There are a variety of meanings of the picker property:
* *None* - picking is disabled for this artist (default)
* bool - if *True* then picking will be enabled and the artist will fire a pick
event if the mouse event is over the artist.
Setting ``pickradius`` will add an epsilon tolerance in points and the artist
will fire off an event if its data is within epsilon of the mouse event. For
some artists like lines and patch collections, the artist may provide
additional data to the pick event that is generated, for example, the indices
of the data within epsilon of the pick event
* function - if picker is callable, it is a user supplied function which
determines whether the artist is hit by the mouse event. ::
hit, props = picker(artist, mouseevent)
to determine the hit test. If the mouse event is over the artist, return
hit=True and props is a dictionary of properties you want added to the
PickEvent attributes.
After you have enabled an artist for picking by setting the "picker"
property, you need to connect to the figure canvas pick_event to get
pick callbacks on mouse press events. For example, ::
def pick_handler(event):
mouseevent = event.mouseevent
artist = event.artist
# now do something with this...
The pick event (matplotlib.backend_bases.PickEvent) which is passed to
your callback is always fired with two attributes:
mouseevent
the mouse event that generate the pick event.
The mouse event in turn has attributes like x and y (the coordinates in
display space, such as pixels from left, bottom) and xdata, ydata (the
coords in data space). Additionally, you can get information about
which buttons were pressed, which keys were pressed, which Axes
the mouse is over, etc. See matplotlib.backend_bases.MouseEvent
for details.
artist
the matplotlib.artist that generated the pick event.
Additionally, certain artists like Line2D and PatchCollection may
attach additional metadata like the indices into the data that meet
the picker criteria (for example, all the points in the line that are within
the specified epsilon tolerance)
The examples below illustrate each of these methods.
.. note::
These examples exercises the interactive capabilities of Matplotlib, and
this will not appear in the static documentation. Please run this code on
your machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
from matplotlib.image import AxesImage
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text
# Fixing random state for reproducibility
np.random.seed(19680801)
# %%
# Simple picking, lines, rectangles and text
# ------------------------------------------
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.set_title('click on points, rectangles or text', picker=True)
ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red'))
line, = ax1.plot(rand(100), 'o', picker=True, pickradius=5)
# Pick the rectangle.
ax2.bar(range(10), rand(10), picker=True)
for label in ax2.get_xticklabels(): # Make the xtick labels pickable.
label.set_picker(True)
def onpick1(event):
if isinstance(event.artist, Line2D):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print('onpick1 line:', np.column_stack([xdata[ind], ydata[ind]]))
elif isinstance(event.artist, Rectangle):
patch = event.artist
print('onpick1 patch:', patch.get_path())
elif isinstance(event.artist, Text):
text = event.artist
print('onpick1 text:', text.get_text())
fig.canvas.mpl_connect('pick_event', onpick1)
# %%
# Picking with a custom hit test function
# ---------------------------------------
# You can define custom pickers by setting picker to a callable function. The
# function has the signature::
#
# hit, props = func(artist, mouseevent)
#
# to determine the hit test. If the mouse event is over the artist, return
# ``hit=True`` and ``props`` is a dictionary of properties you want added to
# the `.PickEvent` attributes.
def line_picker(line, mouseevent):
"""
Find the points within a certain distance from the mouseclick in
data coords and attach some extra attributes, pickx and picky
which are the data points that were picked.
"""
if mouseevent.xdata is None:
return False, dict()
xdata = line.get_xdata()
ydata = line.get_ydata()
maxd = 0.05
d = np.sqrt(
(xdata - mouseevent.xdata)**2 + (ydata - mouseevent.ydata)**2)
ind, = np.nonzero(d <= maxd)
if len(ind):
pickx = xdata[ind]
picky = ydata[ind]
props = dict(ind=ind, pickx=pickx, picky=picky)
return True, props
else:
return False, dict()
def onpick2(event):
print('onpick2 line:', event.pickx, event.picky)
fig, ax = plt.subplots()
ax.set_title('custom picker for line data')
line, = ax.plot(rand(100), rand(100), 'o', picker=line_picker)
fig.canvas.mpl_connect('pick_event', onpick2)
# %%
# Picking on a scatter plot
# -------------------------
# A scatter plot is backed by a `~matplotlib.collections.PathCollection`.
x, y, c, s = rand(4, 100)
def onpick3(event):
ind = event.ind
print('onpick3 scatter:', ind, x[ind], y[ind])
fig, ax = plt.subplots()
ax.scatter(x, y, 100*s, c, picker=True)
fig.canvas.mpl_connect('pick_event', onpick3)
# %%
# Picking images
# --------------
# Images plotted using `.Axes.imshow` are `~matplotlib.image.AxesImage`
# objects.
fig, ax = plt.subplots()
ax.imshow(rand(10, 5), extent=(1, 2, 1, 2), picker=True)
ax.imshow(rand(5, 10), extent=(3, 4, 1, 2), picker=True)
ax.imshow(rand(20, 25), extent=(1, 2, 3, 4), picker=True)
ax.imshow(rand(30, 12), extent=(3, 4, 3, 4), picker=True)
ax.set(xlim=(0, 5), ylim=(0, 5))
def onpick4(event):
artist = event.artist
if isinstance(artist, AxesImage):
im = artist
A = im.get_array()
print('onpick4 image', A.shape)
fig.canvas.mpl_connect('pick_event', onpick4)
plt.show()
| stable__gallery__event_handling__pick_event_demo | 2 | figure_002.png | Pick event demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/pick_event_demo.html#sphx-glr-download-gallery-event-handling-pick-event-demo-py | https://matplotlib.org/stable/_downloads/97bcffbb1f60980e1ed023c1abf6b9f3/pick_event_demo.py | pick_event_demo.py | event_handling | ok | 4 | null | |
"""
===============
Pick event demo
===============
You can enable picking by setting the "picker" property of an artist
(for example, a Matplotlib Line2D, Text, Patch, Polygon, AxesImage,
etc.)
There are a variety of meanings of the picker property:
* *None* - picking is disabled for this artist (default)
* bool - if *True* then picking will be enabled and the artist will fire a pick
event if the mouse event is over the artist.
Setting ``pickradius`` will add an epsilon tolerance in points and the artist
will fire off an event if its data is within epsilon of the mouse event. For
some artists like lines and patch collections, the artist may provide
additional data to the pick event that is generated, for example, the indices
of the data within epsilon of the pick event
* function - if picker is callable, it is a user supplied function which
determines whether the artist is hit by the mouse event. ::
hit, props = picker(artist, mouseevent)
to determine the hit test. If the mouse event is over the artist, return
hit=True and props is a dictionary of properties you want added to the
PickEvent attributes.
After you have enabled an artist for picking by setting the "picker"
property, you need to connect to the figure canvas pick_event to get
pick callbacks on mouse press events. For example, ::
def pick_handler(event):
mouseevent = event.mouseevent
artist = event.artist
# now do something with this...
The pick event (matplotlib.backend_bases.PickEvent) which is passed to
your callback is always fired with two attributes:
mouseevent
the mouse event that generate the pick event.
The mouse event in turn has attributes like x and y (the coordinates in
display space, such as pixels from left, bottom) and xdata, ydata (the
coords in data space). Additionally, you can get information about
which buttons were pressed, which keys were pressed, which Axes
the mouse is over, etc. See matplotlib.backend_bases.MouseEvent
for details.
artist
the matplotlib.artist that generated the pick event.
Additionally, certain artists like Line2D and PatchCollection may
attach additional metadata like the indices into the data that meet
the picker criteria (for example, all the points in the line that are within
the specified epsilon tolerance)
The examples below illustrate each of these methods.
.. note::
These examples exercises the interactive capabilities of Matplotlib, and
this will not appear in the static documentation. Please run this code on
your machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
from matplotlib.image import AxesImage
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text
# Fixing random state for reproducibility
np.random.seed(19680801)
# %%
# Simple picking, lines, rectangles and text
# ------------------------------------------
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.set_title('click on points, rectangles or text', picker=True)
ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red'))
line, = ax1.plot(rand(100), 'o', picker=True, pickradius=5)
# Pick the rectangle.
ax2.bar(range(10), rand(10), picker=True)
for label in ax2.get_xticklabels(): # Make the xtick labels pickable.
label.set_picker(True)
def onpick1(event):
if isinstance(event.artist, Line2D):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print('onpick1 line:', np.column_stack([xdata[ind], ydata[ind]]))
elif isinstance(event.artist, Rectangle):
patch = event.artist
print('onpick1 patch:', patch.get_path())
elif isinstance(event.artist, Text):
text = event.artist
print('onpick1 text:', text.get_text())
fig.canvas.mpl_connect('pick_event', onpick1)
# %%
# Picking with a custom hit test function
# ---------------------------------------
# You can define custom pickers by setting picker to a callable function. The
# function has the signature::
#
# hit, props = func(artist, mouseevent)
#
# to determine the hit test. If the mouse event is over the artist, return
# ``hit=True`` and ``props`` is a dictionary of properties you want added to
# the `.PickEvent` attributes.
def line_picker(line, mouseevent):
"""
Find the points within a certain distance from the mouseclick in
data coords and attach some extra attributes, pickx and picky
which are the data points that were picked.
"""
if mouseevent.xdata is None:
return False, dict()
xdata = line.get_xdata()
ydata = line.get_ydata()
maxd = 0.05
d = np.sqrt(
(xdata - mouseevent.xdata)**2 + (ydata - mouseevent.ydata)**2)
ind, = np.nonzero(d <= maxd)
if len(ind):
pickx = xdata[ind]
picky = ydata[ind]
props = dict(ind=ind, pickx=pickx, picky=picky)
return True, props
else:
return False, dict()
def onpick2(event):
print('onpick2 line:', event.pickx, event.picky)
fig, ax = plt.subplots()
ax.set_title('custom picker for line data')
line, = ax.plot(rand(100), rand(100), 'o', picker=line_picker)
fig.canvas.mpl_connect('pick_event', onpick2)
# %%
# Picking on a scatter plot
# -------------------------
# A scatter plot is backed by a `~matplotlib.collections.PathCollection`.
x, y, c, s = rand(4, 100)
def onpick3(event):
ind = event.ind
print('onpick3 scatter:', ind, x[ind], y[ind])
fig, ax = plt.subplots()
ax.scatter(x, y, 100*s, c, picker=True)
fig.canvas.mpl_connect('pick_event', onpick3)
# %%
# Picking images
# --------------
# Images plotted using `.Axes.imshow` are `~matplotlib.image.AxesImage`
# objects.
fig, ax = plt.subplots()
ax.imshow(rand(10, 5), extent=(1, 2, 1, 2), picker=True)
ax.imshow(rand(5, 10), extent=(3, 4, 1, 2), picker=True)
ax.imshow(rand(20, 25), extent=(1, 2, 3, 4), picker=True)
ax.imshow(rand(30, 12), extent=(3, 4, 3, 4), picker=True)
ax.set(xlim=(0, 5), ylim=(0, 5))
def onpick4(event):
artist = event.artist
if isinstance(artist, AxesImage):
im = artist
A = im.get_array()
print('onpick4 image', A.shape)
fig.canvas.mpl_connect('pick_event', onpick4)
plt.show()
| stable__gallery__event_handling__pick_event_demo | 3 | figure_003.png | Pick event demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/pick_event_demo.html#sphx-glr-download-gallery-event-handling-pick-event-demo-py | https://matplotlib.org/stable/_downloads/97bcffbb1f60980e1ed023c1abf6b9f3/pick_event_demo.py | pick_event_demo.py | event_handling | ok | 4 | null | |
"""
=================
Pick event demo 2
=================
Compute the mean (mu) and standard deviation (sigma) of 100 data sets and plot
mu vs. sigma. When you click on one of the (mu, sigma) points, plot the raw
data from the dataset that generated this point.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
X = np.random.rand(100, 1000)
xs = np.mean(X, axis=1)
ys = np.std(X, axis=1)
fig, ax = plt.subplots()
ax.set_title('click on point to plot time series')
line, = ax.plot(xs, ys, 'o', picker=True, pickradius=5)
def onpick(event):
if event.artist != line:
return
N = len(event.ind)
if not N:
return
figi, axs = plt.subplots(N, squeeze=False)
for ax, dataind in zip(axs.flat, event.ind):
ax.plot(X[dataind])
ax.text(.05, .9, f'mu={xs[dataind]:1.3f}\nsigma={ys[dataind]:1.3f}',
transform=ax.transAxes, va='top')
ax.set_ylim(-0.5, 1.5)
figi.show()
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
| stable__gallery__event_handling__pick_event_demo2 | 0 | figure_000.png | Pick event demo 2 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/pick_event_demo2.html#sphx-glr-download-gallery-event-handling-pick-event-demo2-py | https://matplotlib.org/stable/_downloads/ef768136d19ed35fa2e3968573731c99/pick_event_demo2.py | pick_event_demo2.py | event_handling | ok | 1 | null | |
"""
==============
Polygon editor
==============
This is an example to show how to build cross-GUI applications using
Matplotlib event handling to interact with objects on the canvas.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import numpy as np
from matplotlib.artist import Artist
from matplotlib.lines import Line2D
def dist_point_to_segment(p, s0, s1):
"""
Get the distance from the point *p* to the segment (*s0*, *s1*), where
*p*, *s0*, *s1* are ``[x, y]`` arrays.
"""
s01 = s1 - s0
s0p = p - s0
if (s01 == 0).all():
return np.hypot(*s0p)
# Project onto segment, without going past segment ends.
p1 = s0 + np.clip((s0p @ s01) / (s01 @ s01), 0, 1) * s01
return np.hypot(*(p - p1))
class PolygonInteractor:
"""
A polygon editor.
Key-bindings
't' toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' delete the vertex under point
'i' insert a vertex at point. You must be within epsilon of the
line connecting two existing vertices
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, ax, poly):
if poly.figure is None:
raise RuntimeError('You must first add the polygon to a figure '
'or canvas before defining the interactor')
self.ax = ax
canvas = poly.figure.canvas
self.poly = poly
x, y = zip(*self.poly.xy)
self.line = Line2D(x, y,
marker='o', markerfacecolor='r',
animated=True)
self.ax.add_line(self.line)
self.cid = self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas.mpl_connect('draw_event', self.on_draw)
canvas.mpl_connect('button_press_event', self.on_button_press)
canvas.mpl_connect('key_press_event', self.on_key_press)
canvas.mpl_connect('button_release_event', self.on_button_release)
canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
self.canvas = canvas
def on_draw(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
# do not need to blit here, this will fire before the screen is
# updated
def poly_changed(self, poly):
"""This method is called whenever the pathpatch object is called."""
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def get_ind_under_point(self, event):
"""
Return the index of the point closest to the event position or *None*
if no point is within ``self.epsilon`` to the event position.
"""
# display coords
xy = np.asarray(self.poly.xy)
xyt = self.poly.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.hypot(xt - event.x, yt - event.y)
indseq, = np.nonzero(d == d.min())
ind = indseq[0]
if d[ind] >= self.epsilon:
ind = None
return ind
def on_button_press(self, event):
"""Callback for mouse button presses."""
if not self.showverts:
return
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
def on_button_release(self, event):
"""Callback for mouse button releases."""
if not self.showverts:
return
if event.button != 1:
return
self._ind = None
def on_key_press(self, event):
"""Callback for key presses."""
if not event.inaxes:
return
if event.key == 't':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
elif event.key == 'd':
ind = self.get_ind_under_point(event)
if ind is not None:
self.poly.xy = np.delete(self.poly.xy,
ind, axis=0)
self.line.set_data(zip(*self.poly.xy))
elif event.key == 'i':
xys = self.poly.get_transform().transform(self.poly.xy)
p = event.x, event.y # display coords
for i in range(len(xys) - 1):
s0 = xys[i]
s1 = xys[i + 1]
d = dist_point_to_segment(p, s0, s1)
if d <= self.epsilon:
self.poly.xy = np.insert(
self.poly.xy, i+1,
[event.xdata, event.ydata],
axis=0)
self.line.set_data(zip(*self.poly.xy))
break
if self.line.stale:
self.canvas.draw_idle()
def on_mouse_move(self, event):
"""Callback for mouse movements."""
if not self.showverts:
return
if self._ind is None:
return
if event.inaxes is None:
return
if event.button != 1:
return
x, y = event.xdata, event.ydata
self.poly.xy[self._ind] = x, y
if self._ind == 0:
self.poly.xy[-1] = x, y
elif self._ind == len(self.poly.xy) - 1:
self.poly.xy[0] = x, y
self.line.set_data(zip(*self.poly.xy))
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
if __name__ == '__main__':
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
theta = np.arange(0, 2*np.pi, 0.1)
r = 1.5
xs = r * np.cos(theta)
ys = r * np.sin(theta)
poly = Polygon(np.column_stack([xs, ys]), animated=True)
fig, ax = plt.subplots()
ax.add_patch(poly)
p = PolygonInteractor(ax, poly)
ax.set_title('Click and drag a point to move it')
ax.set_xlim((-2, 2))
ax.set_ylim((-2, 2))
plt.show()
| stable__gallery__event_handling__poly_editor | 0 | figure_000.png | Polygon editor — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/poly_editor.html#sphx-glr-download-gallery-event-handling-poly-editor-py | https://matplotlib.org/stable/_downloads/c45649bbf5126722bd95da5362a4fddc/poly_editor.py | poly_editor.py | event_handling | ok | 1 | null | |
"""
====
Pong
====
A Matplotlib based game of Pong illustrating one way to write interactive
animations that are easily ported to multiple backends.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import time
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randint, randn
from matplotlib.font_manager import FontProperties
instructions = """
Player A: Player B:
'e' up 'i'
'd' down 'k'
press 't' -- close these instructions
(animation will be much faster)
press 'a' -- add a puck
press 'A' -- remove a puck
press '1' -- slow down all pucks
press '2' -- speed up all pucks
press '3' -- slow down distractors
press '4' -- speed up distractors
press ' ' -- reset the first puck
press 'n' -- toggle distractors on/off
press 'g' -- toggle the game on/off
"""
class Pad:
def __init__(self, disp, x, y, type='l'):
self.disp = disp
self.x = x
self.y = y
self.w = .3
self.score = 0
self.xoffset = 0.3
self.yoffset = 0.1
if type == 'r':
self.xoffset *= -1.0
if type == 'l' or type == 'r':
self.signx = -1.0
self.signy = 1.0
else:
self.signx = 1.0
self.signy = -1.0
def contains(self, loc):
return self.disp.get_bbox().contains(loc.x, loc.y)
class Puck:
def __init__(self, disp, pad, field):
self.vmax = .2
self.disp = disp
self.field = field
self._reset(pad)
def _reset(self, pad):
self.x = pad.x + pad.xoffset
if pad.y < 0:
self.y = pad.y + pad.yoffset
else:
self.y = pad.y - pad.yoffset
self.vx = pad.x - self.x
self.vy = pad.y + pad.w/2 - self.y
self._speedlimit()
self._slower()
self._slower()
def update(self, pads):
self.x += self.vx
self.y += self.vy
for pad in pads:
if pad.contains(self):
self.vx *= 1.2 * pad.signx
self.vy *= 1.2 * pad.signy
fudge = .001
# probably cleaner with something like...
if self.x < fudge:
pads[1].score += 1
self._reset(pads[0])
return True
if self.x > 7 - fudge:
pads[0].score += 1
self._reset(pads[1])
return True
if self.y < -1 + fudge or self.y > 1 - fudge:
self.vy *= -1.0
# add some randomness, just to make it interesting
self.vy -= (randn()/300.0 + 1/300.0) * np.sign(self.vy)
self._speedlimit()
return False
def _slower(self):
self.vx /= 5.0
self.vy /= 5.0
def _faster(self):
self.vx *= 5.0
self.vy *= 5.0
def _speedlimit(self):
if self.vx > self.vmax:
self.vx = self.vmax
if self.vx < -self.vmax:
self.vx = -self.vmax
if self.vy > self.vmax:
self.vy = self.vmax
if self.vy < -self.vmax:
self.vy = -self.vmax
class Game:
def __init__(self, ax):
# create the initial line
self.ax = ax
ax.xaxis.set_visible(False)
ax.set_xlim([0, 7])
ax.yaxis.set_visible(False)
ax.set_ylim([-1, 1])
pad_a_x = 0
pad_b_x = .50
pad_a_y = pad_b_y = .30
pad_b_x += 6.3
# pads
pA, = self.ax.barh(pad_a_y, .2,
height=.3, color='k', alpha=.5, edgecolor='b',
lw=2, label="Player B",
animated=True)
pB, = self.ax.barh(pad_b_y, .2,
height=.3, left=pad_b_x, color='k', alpha=.5,
edgecolor='r', lw=2, label="Player A",
animated=True)
# distractors
self.x = np.arange(0, 2.22*np.pi, 0.01)
self.line, = self.ax.plot(self.x, np.sin(self.x), "r",
animated=True, lw=4)
self.line2, = self.ax.plot(self.x, np.cos(self.x), "g",
animated=True, lw=4)
self.line3, = self.ax.plot(self.x, np.cos(self.x), "g",
animated=True, lw=4)
self.line4, = self.ax.plot(self.x, np.cos(self.x), "r",
animated=True, lw=4)
# center line
self.centerline, = self.ax.plot([3.5, 3.5], [1, -1], 'k',
alpha=.5, animated=True, lw=8)
# puck (s)
self.puckdisp = self.ax.scatter([1], [1], label='_nolegend_',
s=200, c='g',
alpha=.9, animated=True)
self.canvas = self.ax.figure.canvas
self.background = None
self.cnt = 0
self.distract = True
self.res = 100.0
self.on = False
self.inst = True # show instructions from the beginning
self.pads = [Pad(pA, pad_a_x, pad_a_y),
Pad(pB, pad_b_x, pad_b_y, 'r')]
self.pucks = []
self.i = self.ax.annotate(instructions, (.5, 0.5),
name='monospace',
verticalalignment='center',
horizontalalignment='center',
multialignment='left',
xycoords='axes fraction',
animated=False)
self.canvas.mpl_connect('key_press_event', self.on_key_press)
def draw(self):
draw_artist = self.ax.draw_artist
if self.background is None:
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
# restore the clean slate background
self.canvas.restore_region(self.background)
# show the distractors
if self.distract:
self.line.set_ydata(np.sin(self.x + self.cnt/self.res))
self.line2.set_ydata(np.cos(self.x - self.cnt/self.res))
self.line3.set_ydata(np.tan(self.x + self.cnt/self.res))
self.line4.set_ydata(np.tan(self.x - self.cnt/self.res))
draw_artist(self.line)
draw_artist(self.line2)
draw_artist(self.line3)
draw_artist(self.line4)
# pucks and pads
if self.on:
self.ax.draw_artist(self.centerline)
for pad in self.pads:
pad.disp.set_y(pad.y)
pad.disp.set_x(pad.x)
self.ax.draw_artist(pad.disp)
for puck in self.pucks:
if puck.update(self.pads):
# we only get here if someone scored
self.pads[0].disp.set_label(f" {self.pads[0].score}")
self.pads[1].disp.set_label(f" {self.pads[1].score}")
self.ax.legend(loc='center', framealpha=.2,
facecolor='0.5',
prop=FontProperties(size='xx-large',
weight='bold'))
self.background = None
self.ax.figure.canvas.draw_idle()
return
puck.disp.set_offsets([[puck.x, puck.y]])
self.ax.draw_artist(puck.disp)
# just redraw the Axes rectangle
self.canvas.blit(self.ax.bbox)
self.canvas.flush_events()
if self.cnt == 50000:
# just so we don't get carried away
print("...and you've been playing for too long!!!")
plt.close()
self.cnt += 1
def on_key_press(self, event):
if event.key == '3':
self.res *= 5.0
if event.key == '4':
self.res /= 5.0
if event.key == 'e':
self.pads[0].y += .1
if self.pads[0].y > 1 - .3:
self.pads[0].y = 1 - .3
if event.key == 'd':
self.pads[0].y -= .1
if self.pads[0].y < -1:
self.pads[0].y = -1
if event.key == 'i':
self.pads[1].y += .1
if self.pads[1].y > 1 - .3:
self.pads[1].y = 1 - .3
if event.key == 'k':
self.pads[1].y -= .1
if self.pads[1].y < -1:
self.pads[1].y = -1
if event.key == 'a':
self.pucks.append(Puck(self.puckdisp,
self.pads[randint(2)],
self.ax.bbox))
if event.key == 'A' and len(self.pucks):
self.pucks.pop()
if event.key == ' ' and len(self.pucks):
self.pucks[0]._reset(self.pads[randint(2)])
if event.key == '1':
for p in self.pucks:
p._slower()
if event.key == '2':
for p in self.pucks:
p._faster()
if event.key == 'n':
self.distract = not self.distract
if event.key == 'g':
self.on = not self.on
if event.key == 't':
self.inst = not self.inst
self.i.set_visible(not self.i.get_visible())
self.background = None
self.canvas.draw_idle()
if event.key == 'q':
plt.close()
fig, ax = plt.subplots()
canvas = ax.figure.canvas
animation = Game(ax)
# disable the default key bindings
if fig.canvas.manager.key_press_handler_id is not None:
canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)
# reset the blitting background on redraw
def on_redraw(event):
animation.background = None
# bootstrap after the first draw
def start_anim(event):
canvas.mpl_disconnect(start_anim.cid)
start_anim.timer.add_callback(animation.draw)
start_anim.timer.start()
canvas.mpl_connect('draw_event', on_redraw)
start_anim.cid = canvas.mpl_connect('draw_event', start_anim)
start_anim.timer = animation.canvas.new_timer(interval=1)
tstart = time.time()
plt.show()
print('FPS: %f' % (animation.cnt/(time.time() - tstart)))
| stable__gallery__event_handling__pong_sgskip | 0 | figure_000.png | Pong — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/pong_sgskip.html#sphx-glr-download-gallery-event-handling-pong-sgskip-py | https://matplotlib.org/stable/_downloads/b047032cf62d3ac8a0705adf298a6fb8/pong_sgskip.py | pong_sgskip.py | event_handling | ok | 1 | null | |
"""
===============
Resampling Data
===============
Downsampling lowers the sample rate or sample size of a signal. In
this tutorial, the signal is downsampled when the plot is adjusted
through dragging and zooming.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
# A class that will downsample the data and recompute when zoomed.
class DataDisplayDownsampler:
def __init__(self, xdata, y1data, y2data):
self.origY1Data = y1data
self.origY2Data = y2data
self.origXData = xdata
self.max_points = 50
self.delta = xdata[-1] - xdata[0]
def plot(self, ax):
x, y1, y2 = self._downsample(self.origXData.min(), self.origXData.max())
(self.line,) = ax.plot(x, y1, 'o-')
self.poly_collection = ax.fill_between(x, y1, y2, step="pre", color="r")
def _downsample(self, xstart, xend):
# get the points in the view range
mask = (self.origXData > xstart) & (self.origXData < xend)
# dilate the mask by one to catch the points just outside
# of the view range to not truncate the line
mask = np.convolve([1, 1, 1], mask, mode='same').astype(bool)
# sort out how many points to drop
ratio = max(np.sum(mask) // self.max_points, 1)
# mask data
xdata = self.origXData[mask]
y1data = self.origY1Data[mask]
y2data = self.origY2Data[mask]
# downsample data
xdata = xdata[::ratio]
y1data = y1data[::ratio]
y2data = y2data[::ratio]
print(f"using {len(y1data)} of {np.sum(mask)} visible points")
return xdata, y1data, y2data
def update(self, ax):
# Update the artists
lims = ax.viewLim
if abs(lims.width - self.delta) > 1e-8:
self.delta = lims.width
xstart, xend = lims.intervalx
x, y1, y2 = self._downsample(xstart, xend)
self.line.set_data(x, y1)
self.poly_collection.set_data(x, y1, y2, step="pre")
ax.figure.canvas.draw_idle()
# Create a signal
xdata = np.linspace(16, 365, (365-16)*4)
y1data = np.sin(2*np.pi*xdata/153) + np.cos(2*np.pi*xdata/127)
y2data = y1data + .2
d = DataDisplayDownsampler(xdata, y1data, y2data)
fig, ax = plt.subplots()
# Hook up the line
d.plot(ax)
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Connect for changing the view limits
ax.callbacks.connect('xlim_changed', d.update)
ax.set_xlim(16, 365)
plt.show()
# %%
# .. tags:: interactivity: zoom, event-handling
| stable__gallery__event_handling__resample | 0 | figure_000.png | Resampling Data — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/resample.html#sphx-glr-download-gallery-event-handling-resample-py | https://matplotlib.org/stable/_downloads/58860601ba402c68bbd750a99c1bc502/resample.py | resample.py | event_handling | ok | 1 | null | |
"""
======
Timers
======
Simple example of using general timer objects. This is used to update
the time placed in the title of the figure.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
def update_title(axes):
axes.set_title(datetime.now())
axes.figure.canvas.draw()
fig, ax = plt.subplots()
x = np.linspace(-3, 3)
ax.plot(x, x ** 2)
# Create a new timer object. Set the interval to 100 milliseconds
# (1000 is default) and tell the timer what function should be called.
timer = fig.canvas.new_timer(interval=100)
timer.add_callback(update_title, ax)
timer.start()
# Or could start the timer on first figure draw:
# def start_timer(event):
# timer.start()
# fig.canvas.mpl_disconnect(drawid)
# drawid = fig.canvas.mpl_connect('draw_event', start_timer)
plt.show()
| stable__gallery__event_handling__timers | 0 | figure_000.png | Timers — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/timers.html#timers | https://matplotlib.org/stable/_downloads/891c0deb05e636b4ec0f64f30bee6d1d/timers.py | timers.py | event_handling | ok | 1 | null | |
"""
====================
Trifinder Event Demo
====================
Example showing the use of a TriFinder object. As the mouse is moved over the
triangulation, the triangle under the cursor is highlighted and the index of
the triangle is displayed in the plot title.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
from matplotlib.tri import Triangulation
def update_polygon(tri):
if tri == -1:
points = [0, 0, 0]
else:
points = triang.triangles[tri]
xs = triang.x[points]
ys = triang.y[points]
polygon.set_xy(np.column_stack([xs, ys]))
def on_mouse_move(event):
if event.inaxes is None:
tri = -1
else:
tri = trifinder(event.xdata, event.ydata)
update_polygon(tri)
ax.set_title(f'In triangle {tri}')
event.canvas.draw()
# Create a Triangulation.
n_angles = 16
n_radii = 5
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi / n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
triang = Triangulation(x, y)
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
# Use the triangulation's default TriFinder object.
trifinder = triang.get_trifinder()
# Setup plot and callbacks.
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
ax.triplot(triang, 'bo-')
polygon = Polygon([[0, 0], [0, 0]], facecolor='y') # dummy data for (xs, ys)
update_polygon(-1)
ax.add_patch(polygon)
fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)
plt.show()
| stable__gallery__event_handling__trifinder_event_demo | 0 | figure_000.png | Trifinder Event Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/trifinder_event_demo.html#trifinder-event-demo | https://matplotlib.org/stable/_downloads/e0a27ecefca35017e6100a8601ded4d7/trifinder_event_demo.py | trifinder_event_demo.py | event_handling | ok | 1 | null | |
"""
========
Viewlims
========
Creates two identical panels. Zooming in on the right panel will show
a rectangle in the first panel, denoting the zoomed region.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import functools
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle
# A class that will regenerate a fractal set as we zoom in, so that you
# can actually see the increasing detail. A box in the left panel will show
# the area to which we are zoomed.
class MandelbrotDisplay:
def __init__(self, h=500, w=500, niter=50, radius=2., power=2):
self.height = h
self.width = w
self.niter = niter
self.radius = radius
self.power = power
def compute_image(self, xlim, ylim):
self.x = np.linspace(*xlim, self.width)
self.y = np.linspace(*ylim, self.height).reshape(-1, 1)
c = self.x + 1.0j * self.y
threshold_time = np.zeros((self.height, self.width))
z = np.zeros(threshold_time.shape, dtype=complex)
mask = np.ones(threshold_time.shape, dtype=bool)
for i in range(self.niter):
z[mask] = z[mask]**self.power + c[mask]
mask = (np.abs(z) < self.radius)
threshold_time += mask
return threshold_time
def ax_update(self, ax):
ax.set_autoscale_on(False) # Otherwise, infinite loop
# Get the number of points from the number of pixels in the window
self.width, self.height = ax.patch.get_window_extent().size.round().astype(int)
# Update the image object with our new data and extent
ax.images[-1].set(data=self.compute_image(ax.get_xlim(), ax.get_ylim()),
extent=(*ax.get_xlim(), *ax.get_ylim()))
ax.figure.canvas.draw_idle()
md = MandelbrotDisplay()
fig1, (ax_full, ax_zoom) = plt.subplots(1, 2)
ax_zoom.imshow([[0]], origin="lower") # Empty initial image.
ax_zoom.set_title("Zoom here")
rect = Rectangle(
[0, 0], 0, 0, facecolor="none", edgecolor="black", linewidth=1.0)
ax_full.add_patch(rect)
def update_rect(rect, ax): # Let the rectangle track the bounds of the zoom axes.
xlo, xhi = ax.get_xlim()
ylo, yhi = ax.get_ylim()
rect.set_bounds((xlo, ylo, xhi - xlo, yhi - ylo))
ax.figure.canvas.draw_idle()
# Connect for changing the view limits.
ax_zoom.callbacks.connect("xlim_changed", functools.partial(update_rect, rect))
ax_zoom.callbacks.connect("ylim_changed", functools.partial(update_rect, rect))
ax_zoom.callbacks.connect("xlim_changed", md.ax_update)
ax_zoom.callbacks.connect("ylim_changed", md.ax_update)
# Initialize: trigger image computation by setting view limits; set colormap limits;
# copy image to full view.
ax_zoom.set(xlim=(-2, .5), ylim=(-1.25, 1.25))
im = ax_zoom.images[0]
ax_zoom.images[0].set(clim=(im.get_array().min(), im.get_array().max()))
ax_full.imshow(im.get_array(), extent=im.get_extent(), origin="lower")
plt.show()
| stable__gallery__event_handling__viewlims | 0 | figure_000.png | Viewlims — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/viewlims.html#viewlims | https://matplotlib.org/stable/_downloads/b6082016b560fa99854e3efaf1afb469/viewlims.py | viewlims.py | event_handling | ok | 1 | null | |
"""
========================
Zoom modifies other Axes
========================
This example shows how to connect events in one window, for example, a mouse
press, to another figure window.
If you click on a point in the first window, the z and y limits of the second
will be adjusted so that the center of the zoom in the second window will be
the (x, y) coordinates of the clicked point.
Note the diameter of the circles in the scatter are defined in points**2, so
their size is independent of the zoom.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
figsrc, axsrc = plt.subplots(figsize=(3.7, 3.7))
figzoom, axzoom = plt.subplots(figsize=(3.7, 3.7))
axsrc.set(xlim=(0, 1), ylim=(0, 1), autoscale_on=False,
title='Click to zoom')
axzoom.set(xlim=(0.45, 0.55), ylim=(0.4, 0.6), autoscale_on=False,
title='Zoom window')
x, y, s, c = np.random.rand(4, 200)
s *= 200
axsrc.scatter(x, y, s, c)
axzoom.scatter(x, y, s, c)
def on_press(event):
if event.button != 1:
return
x, y = event.xdata, event.ydata
axzoom.set_xlim(x - 0.1, x + 0.1)
axzoom.set_ylim(y - 0.1, y + 0.1)
figzoom.canvas.draw()
figsrc.canvas.mpl_connect('button_press_event', on_press)
plt.show()
| stable__gallery__event_handling__zoom_window | 0 | figure_000.png | Zoom modifies other Axes — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/zoom_window.html#zoom-modifies-other-axes | https://matplotlib.org/stable/_downloads/a319bec4b46d9f1a6ea08e8eaa61cc5b/zoom_window.py | zoom_window.py | event_handling | ok | 2 | null | |
"""
========================
Zoom modifies other Axes
========================
This example shows how to connect events in one window, for example, a mouse
press, to another figure window.
If you click on a point in the first window, the z and y limits of the second
will be adjusted so that the center of the zoom in the second window will be
the (x, y) coordinates of the clicked point.
Note the diameter of the circles in the scatter are defined in points**2, so
their size is independent of the zoom.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
will not appear in the static documentation. Please run this code on your
machine to see the interactivity.
You can copy and paste individual parts, or download the entire example
using the link at the bottom of the page.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
figsrc, axsrc = plt.subplots(figsize=(3.7, 3.7))
figzoom, axzoom = plt.subplots(figsize=(3.7, 3.7))
axsrc.set(xlim=(0, 1), ylim=(0, 1), autoscale_on=False,
title='Click to zoom')
axzoom.set(xlim=(0.45, 0.55), ylim=(0.4, 0.6), autoscale_on=False,
title='Zoom window')
x, y, s, c = np.random.rand(4, 200)
s *= 200
axsrc.scatter(x, y, s, c)
axzoom.scatter(x, y, s, c)
def on_press(event):
if event.button != 1:
return
x, y = event.xdata, event.ydata
axzoom.set_xlim(x - 0.1, x + 0.1)
axzoom.set_ylim(y - 0.1, y + 0.1)
figzoom.canvas.draw()
figsrc.canvas.mpl_connect('button_press_event', on_press)
plt.show()
| stable__gallery__event_handling__zoom_window | 1 | figure_001.png | Zoom modifies other Axes — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/event_handling/zoom_window.html#zoom-modifies-other-axes | https://matplotlib.org/stable/_downloads/a319bec4b46d9f1a6ea08e8eaa61cc5b/zoom_window.py | zoom_window.py | event_handling | ok | 2 | null | |
"""
============================
Affine transform of an image
============================
Prepending an affine transformation (`~.transforms.Affine2D`) to the :ref:`data
transform <data-coords>` of an image allows to manipulate the image's shape and
orientation. This is an example of the concept of :ref:`transform chaining
<transformation-pipeline>`.
The image of the output should have its boundary match the dashed yellow
rectangle.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms as mtransforms
def get_image():
delta = 0.25
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2)
return Z
def do_plot(ax, Z, transform):
im = ax.imshow(Z, interpolation='none',
origin='lower',
extent=[-2, 4, -3, 2], clip_on=True)
trans_data = transform + ax.transData
im.set_transform(trans_data)
# display intended extent of the image
x1, x2, y1, y2 = im.get_extent()
ax.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], "y--",
transform=trans_data)
ax.set_xlim(-5, 5)
ax.set_ylim(-4, 4)
# prepare image and figure
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
Z = get_image()
# image rotation
do_plot(ax1, Z, mtransforms.Affine2D().rotate_deg(30))
# image skew
do_plot(ax2, Z, mtransforms.Affine2D().skew_deg(30, 15))
# scale and reflection
do_plot(ax3, Z, mtransforms.Affine2D().scale(-1, .5))
# everything and a translation
do_plot(ax4, Z, mtransforms.Affine2D().
rotate_deg(30).skew_deg(30, 15).scale(-1, .5).translate(.5, -1))
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.imshow` / `matplotlib.pyplot.imshow`
# - `matplotlib.transforms.Affine2D`
| stable__gallery__images_contours_and_fields__affine_image | 0 | figure_000.png | Affine transform of an image — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/affine_image.html#sphx-glr-download-gallery-images-contours-and-fields-affine-image-py | https://matplotlib.org/stable/_downloads/a0ba87a82fe3b31fd9b06f25a2c11522/affine_image.py | affine_image.py | images_contours_and_fields | ok | 1 | null | |
"""
==========
Wind barbs
==========
Demonstration of wind barb plots.
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 5)
X, Y = np.meshgrid(x, x)
U, V = 12 * X, 12 * Y
data = [(-1.5, .5, -6, -6),
(1, -1, -46, 46),
(-3, -1, 11, -11),
(1, 1.5, 80, 80),
(0.5, 0.25, 25, 15),
(-1.5, -0.5, -5, 40)]
data = np.array(data, dtype=[('x', np.float32), ('y', np.float32),
('u', np.float32), ('v', np.float32)])
fig1, axs1 = plt.subplots(nrows=2, ncols=2)
# Default parameters, uniform grid
axs1[0, 0].barbs(X, Y, U, V)
# Arbitrary set of vectors, make them longer and change the pivot point
# (point around which they're rotated) to be the middle
axs1[0, 1].barbs(
data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')
# Showing colormapping with uniform grid. Fill the circle for an empty barb,
# don't round the values, and change some of the size parameters
axs1[1, 0].barbs(
X, Y, U, V, np.sqrt(U ** 2 + V ** 2), fill_empty=True, rounding=False,
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
# Change colors as well as the increments for parts of the barbs
axs1[1, 1].barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',
barbcolor=['b', 'g'], flip_barb=True,
barb_increments=dict(half=10, full=20, flag=100))
# Masked arrays are also supported
masked_u = np.ma.masked_array(data['u'])
masked_u[4] = 1000 # Bad value that should not be plotted when masked
masked_u[4] = np.ma.masked
# %%
# Identical plot to panel 2 in the first figure, but with the point at
# (0.5, 0.25) missing (masked)
fig2, ax2 = plt.subplots()
ax2.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.barbs` / `matplotlib.pyplot.barbs`
| stable__gallery__images_contours_and_fields__barb_demo | 0 | figure_000.png | Wind barbs — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/barb_demo.html#wind-barbs | https://matplotlib.org/stable/_downloads/bd67ba4ff04d8ab5785fdcdf1d0f2c9c/barb_demo.py | barb_demo.py | images_contours_and_fields | ok | 2 | null | |
"""
==========
Wind barbs
==========
Demonstration of wind barb plots.
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 5)
X, Y = np.meshgrid(x, x)
U, V = 12 * X, 12 * Y
data = [(-1.5, .5, -6, -6),
(1, -1, -46, 46),
(-3, -1, 11, -11),
(1, 1.5, 80, 80),
(0.5, 0.25, 25, 15),
(-1.5, -0.5, -5, 40)]
data = np.array(data, dtype=[('x', np.float32), ('y', np.float32),
('u', np.float32), ('v', np.float32)])
fig1, axs1 = plt.subplots(nrows=2, ncols=2)
# Default parameters, uniform grid
axs1[0, 0].barbs(X, Y, U, V)
# Arbitrary set of vectors, make them longer and change the pivot point
# (point around which they're rotated) to be the middle
axs1[0, 1].barbs(
data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')
# Showing colormapping with uniform grid. Fill the circle for an empty barb,
# don't round the values, and change some of the size parameters
axs1[1, 0].barbs(
X, Y, U, V, np.sqrt(U ** 2 + V ** 2), fill_empty=True, rounding=False,
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
# Change colors as well as the increments for parts of the barbs
axs1[1, 1].barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',
barbcolor=['b', 'g'], flip_barb=True,
barb_increments=dict(half=10, full=20, flag=100))
# Masked arrays are also supported
masked_u = np.ma.masked_array(data['u'])
masked_u[4] = 1000 # Bad value that should not be plotted when masked
masked_u[4] = np.ma.masked
# %%
# Identical plot to panel 2 in the first figure, but with the point at
# (0.5, 0.25) missing (masked)
fig2, ax2 = plt.subplots()
ax2.barbs(data['x'], data['y'], masked_u, data['v'], length=8, pivot='middle')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.barbs` / `matplotlib.pyplot.barbs`
| stable__gallery__images_contours_and_fields__barb_demo | 1 | figure_001.png | Wind barbs — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/barb_demo.html#wind-barbs | https://matplotlib.org/stable/_downloads/bd67ba4ff04d8ab5785fdcdf1d0f2c9c/barb_demo.py | barb_demo.py | images_contours_and_fields | ok | 2 | null | |
"""
=======
Barcode
=======
This demo shows how to produce a bar code.
The figure size is calculated so that the width in pixels is a multiple of the
number of data points to prevent interpolation artifacts. Additionally, the
``Axes`` is defined to span the whole figure and all ``Axis`` are turned off.
The data itself is rendered with `~.Axes.imshow` using
- ``code.reshape(1, -1)`` to turn the data into a 2D array with one row.
- ``imshow(..., aspect='auto')`` to allow for non-square pixels.
- ``imshow(..., interpolation='nearest')`` to prevent blurred edges. This
should not happen anyway because we fine-tuned the figure width in pixels,
but just to be safe.
"""
import matplotlib.pyplot as plt
import numpy as np
code = np.array([
1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1,
0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0,
1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1,
1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1])
pixel_per_bar = 4
dpi = 100
fig = plt.figure(figsize=(len(code) * pixel_per_bar / dpi, 2), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1]) # span the whole figure
ax.set_axis_off()
ax.imshow(code.reshape(1, -1), cmap='binary', aspect='auto',
interpolation='nearest')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.imshow` / `matplotlib.pyplot.imshow`
# - `matplotlib.figure.Figure.add_axes`
| stable__gallery__images_contours_and_fields__barcode_demo | 0 | figure_000.png | Barcode — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/barcode_demo.html#sphx-glr-download-gallery-images-contours-and-fields-barcode-demo-py | https://matplotlib.org/stable/_downloads/7773e82aca62130e700b147505be37d4/barcode_demo.py | barcode_demo.py | images_contours_and_fields | ok | 1 | null | |
"""
========================================
Interactive adjustment of colormap range
========================================
Demonstration of how a colorbar can be used to interactively adjust the
range of colormapping on an image. To use the interactive feature, you must
be in either zoom mode (magnifying glass toolbar button) or
pan mode (4-way arrow toolbar button) and click inside the colorbar.
When zooming, the bounding box of the zoom region defines the new vmin and
vmax of the norm. Zooming using the right mouse button will expand the
vmin and vmax proportionally to the selected region, in the same manner that
one can zoom out on an axis. When panning, the vmin and vmax of the norm are
both shifted according to the direction of movement. The
Home/Back/Forward buttons can also be used to get back to a previous state.
.. redirect-from:: /gallery/userdemo/colormap_interactive_adjustment
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 2 * np.pi, 1024)
data2d = np.sin(t)[:, np.newaxis] * np.cos(t)[np.newaxis, :]
fig, ax = plt.subplots()
im = ax.imshow(data2d)
ax.set_title('Pan on the colorbar to shift the color mapping\n'
'Zoom on the colorbar to scale the color mapping')
fig.colorbar(im, ax=ax, label='Interactive colorbar')
plt.show()
| stable__gallery__images_contours_and_fields__colormap_interactive_adjustment | 0 | figure_000.png | Interactive adjustment of colormap range — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/colormap_interactive_adjustment.html#sphx-glr-download-gallery-images-contours-and-fields-colormap-interactive-adjustment-py | https://matplotlib.org/stable/_downloads/514daa758297484d0d616371a934225a/colormap_interactive_adjustment.py | colormap_interactive_adjustment.py | images_contours_and_fields | ok | 1 | null | |
"""
=======================
Colormap normalizations
=======================
Demonstration of using norm to map colormaps onto data in non-linear ways.
.. redirect-from:: /gallery/userdemo/colormap_normalizations
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
N = 100
# %%
# LogNorm
# -------
# This example data has a low hump with a spike coming out of its center. If plotted
# using a linear colour scale, then only the spike will be visible. To see both hump and
# spike, this requires the z/colour axis on a log scale.
#
# Instead of transforming the data with ``pcolor(log10(Z))``, the color mapping can be
# made logarithmic using a `.LogNorm`.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()))
fig.colorbar(pcm, ax=ax[1], extend='max', label='LogNorm')
# %%
# PowerNorm
# ---------
# This example data mixes a power-law trend in X with a rectified sine wave in Y. If
# plotted using a linear colour scale, then the power-law trend in X partially obscures
# the sine wave in Y.
#
# The power law can be removed using a `.PowerNorm`.
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z = (1 + np.sin(Y * 10)) * X**2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.PowerNorm(gamma=0.5))
fig.colorbar(pcm, ax=ax[1], extend='max', label='PowerNorm')
# %%
# SymLogNorm
# ----------
# This example data has two humps, one negative and one positive, The positive hump has
# 5 times the amplitude of the negative. If plotted with a linear colour scale, then
# the detail in the negative hump is obscured.
#
# Here we logarithmically scale the positive and negative data separately with
# `.SymLogNorm`.
#
# Note that colorbar labels do not come out looking very good.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (5 * Z1 - Z2) * 2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=colors.SymLogNorm(linthresh=0.015,
vmin=-10.0, vmax=10.0, base=10))
fig.colorbar(pcm, ax=ax[1], extend='both', label='SymLogNorm')
# %%
# Custom Norm
# -----------
# Alternatively, the above example data can be scaled with a customized normalization.
# This one normalizes the negative data differently from the positive.
# Example of making your own norm. Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
super().__init__(vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
# %%
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=MidpointNormalize(midpoint=0))
fig.colorbar(pcm, ax=ax[1], extend='both', label='Custom norm')
# %%
# BoundaryNorm
# ------------
# For arbitrarily dividing the color scale, the `.BoundaryNorm` may be used; by
# providing the boundaries for colors, this norm puts the first color in between the
# first pair, the second color between the second pair, etc.
fig, ax = plt.subplots(3, 1, layout='constrained')
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical',
label='linear scaling')
# Evenly-spaced bounds gives a contour-like effect.
bounds = np.linspace(-2, 2, 11)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical',
label='BoundaryNorm\nlinspace(-2, 2, 11)')
# Unevenly-spaced bounds changes the colormapping.
bounds = np.array([-1, -0.5, 0, 2.5, 5])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical',
label='BoundaryNorm\n[-1, -0.5, 0, 2.5, 5]')
plt.show()
| stable__gallery__images_contours_and_fields__colormap_normalizations | 0 | figure_000.png | Colormap normalizations — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/colormap_normalizations.html#symlognorm | https://matplotlib.org/stable/_downloads/7246e4cd4f0a538ca175e2afddd49c5e/colormap_normalizations.py | colormap_normalizations.py | images_contours_and_fields | ok | 5 | null | |
"""
=======================
Colormap normalizations
=======================
Demonstration of using norm to map colormaps onto data in non-linear ways.
.. redirect-from:: /gallery/userdemo/colormap_normalizations
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
N = 100
# %%
# LogNorm
# -------
# This example data has a low hump with a spike coming out of its center. If plotted
# using a linear colour scale, then only the spike will be visible. To see both hump and
# spike, this requires the z/colour axis on a log scale.
#
# Instead of transforming the data with ``pcolor(log10(Z))``, the color mapping can be
# made logarithmic using a `.LogNorm`.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()))
fig.colorbar(pcm, ax=ax[1], extend='max', label='LogNorm')
# %%
# PowerNorm
# ---------
# This example data mixes a power-law trend in X with a rectified sine wave in Y. If
# plotted using a linear colour scale, then the power-law trend in X partially obscures
# the sine wave in Y.
#
# The power law can be removed using a `.PowerNorm`.
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z = (1 + np.sin(Y * 10)) * X**2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.PowerNorm(gamma=0.5))
fig.colorbar(pcm, ax=ax[1], extend='max', label='PowerNorm')
# %%
# SymLogNorm
# ----------
# This example data has two humps, one negative and one positive, The positive hump has
# 5 times the amplitude of the negative. If plotted with a linear colour scale, then
# the detail in the negative hump is obscured.
#
# Here we logarithmically scale the positive and negative data separately with
# `.SymLogNorm`.
#
# Note that colorbar labels do not come out looking very good.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (5 * Z1 - Z2) * 2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=colors.SymLogNorm(linthresh=0.015,
vmin=-10.0, vmax=10.0, base=10))
fig.colorbar(pcm, ax=ax[1], extend='both', label='SymLogNorm')
# %%
# Custom Norm
# -----------
# Alternatively, the above example data can be scaled with a customized normalization.
# This one normalizes the negative data differently from the positive.
# Example of making your own norm. Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
super().__init__(vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
# %%
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=MidpointNormalize(midpoint=0))
fig.colorbar(pcm, ax=ax[1], extend='both', label='Custom norm')
# %%
# BoundaryNorm
# ------------
# For arbitrarily dividing the color scale, the `.BoundaryNorm` may be used; by
# providing the boundaries for colors, this norm puts the first color in between the
# first pair, the second color between the second pair, etc.
fig, ax = plt.subplots(3, 1, layout='constrained')
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical',
label='linear scaling')
# Evenly-spaced bounds gives a contour-like effect.
bounds = np.linspace(-2, 2, 11)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical',
label='BoundaryNorm\nlinspace(-2, 2, 11)')
# Unevenly-spaced bounds changes the colormapping.
bounds = np.array([-1, -0.5, 0, 2.5, 5])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical',
label='BoundaryNorm\n[-1, -0.5, 0, 2.5, 5]')
plt.show()
| stable__gallery__images_contours_and_fields__colormap_normalizations | 1 | figure_001.png | Colormap normalizations — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/colormap_normalizations.html#symlognorm | https://matplotlib.org/stable/_downloads/7246e4cd4f0a538ca175e2afddd49c5e/colormap_normalizations.py | colormap_normalizations.py | images_contours_and_fields | ok | 5 | null | |
"""
=======================
Colormap normalizations
=======================
Demonstration of using norm to map colormaps onto data in non-linear ways.
.. redirect-from:: /gallery/userdemo/colormap_normalizations
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
N = 100
# %%
# LogNorm
# -------
# This example data has a low hump with a spike coming out of its center. If plotted
# using a linear colour scale, then only the spike will be visible. To see both hump and
# spike, this requires the z/colour axis on a log scale.
#
# Instead of transforming the data with ``pcolor(log10(Z))``, the color mapping can be
# made logarithmic using a `.LogNorm`.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()))
fig.colorbar(pcm, ax=ax[1], extend='max', label='LogNorm')
# %%
# PowerNorm
# ---------
# This example data mixes a power-law trend in X with a rectified sine wave in Y. If
# plotted using a linear colour scale, then the power-law trend in X partially obscures
# the sine wave in Y.
#
# The power law can be removed using a `.PowerNorm`.
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z = (1 + np.sin(Y * 10)) * X**2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.PowerNorm(gamma=0.5))
fig.colorbar(pcm, ax=ax[1], extend='max', label='PowerNorm')
# %%
# SymLogNorm
# ----------
# This example data has two humps, one negative and one positive, The positive hump has
# 5 times the amplitude of the negative. If plotted with a linear colour scale, then
# the detail in the negative hump is obscured.
#
# Here we logarithmically scale the positive and negative data separately with
# `.SymLogNorm`.
#
# Note that colorbar labels do not come out looking very good.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (5 * Z1 - Z2) * 2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=colors.SymLogNorm(linthresh=0.015,
vmin=-10.0, vmax=10.0, base=10))
fig.colorbar(pcm, ax=ax[1], extend='both', label='SymLogNorm')
# %%
# Custom Norm
# -----------
# Alternatively, the above example data can be scaled with a customized normalization.
# This one normalizes the negative data differently from the positive.
# Example of making your own norm. Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
super().__init__(vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
# %%
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=MidpointNormalize(midpoint=0))
fig.colorbar(pcm, ax=ax[1], extend='both', label='Custom norm')
# %%
# BoundaryNorm
# ------------
# For arbitrarily dividing the color scale, the `.BoundaryNorm` may be used; by
# providing the boundaries for colors, this norm puts the first color in between the
# first pair, the second color between the second pair, etc.
fig, ax = plt.subplots(3, 1, layout='constrained')
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical',
label='linear scaling')
# Evenly-spaced bounds gives a contour-like effect.
bounds = np.linspace(-2, 2, 11)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical',
label='BoundaryNorm\nlinspace(-2, 2, 11)')
# Unevenly-spaced bounds changes the colormapping.
bounds = np.array([-1, -0.5, 0, 2.5, 5])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical',
label='BoundaryNorm\n[-1, -0.5, 0, 2.5, 5]')
plt.show()
| stable__gallery__images_contours_and_fields__colormap_normalizations | 2 | figure_002.png | Colormap normalizations — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/colormap_normalizations.html#symlognorm | https://matplotlib.org/stable/_downloads/7246e4cd4f0a538ca175e2afddd49c5e/colormap_normalizations.py | colormap_normalizations.py | images_contours_and_fields | ok | 5 | null | |
"""
=======================
Colormap normalizations
=======================
Demonstration of using norm to map colormaps onto data in non-linear ways.
.. redirect-from:: /gallery/userdemo/colormap_normalizations
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
N = 100
# %%
# LogNorm
# -------
# This example data has a low hump with a spike coming out of its center. If plotted
# using a linear colour scale, then only the spike will be visible. To see both hump and
# spike, this requires the z/colour axis on a log scale.
#
# Instead of transforming the data with ``pcolor(log10(Z))``, the color mapping can be
# made logarithmic using a `.LogNorm`.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()))
fig.colorbar(pcm, ax=ax[1], extend='max', label='LogNorm')
# %%
# PowerNorm
# ---------
# This example data mixes a power-law trend in X with a rectified sine wave in Y. If
# plotted using a linear colour scale, then the power-law trend in X partially obscures
# the sine wave in Y.
#
# The power law can be removed using a `.PowerNorm`.
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z = (1 + np.sin(Y * 10)) * X**2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.PowerNorm(gamma=0.5))
fig.colorbar(pcm, ax=ax[1], extend='max', label='PowerNorm')
# %%
# SymLogNorm
# ----------
# This example data has two humps, one negative and one positive, The positive hump has
# 5 times the amplitude of the negative. If plotted with a linear colour scale, then
# the detail in the negative hump is obscured.
#
# Here we logarithmically scale the positive and negative data separately with
# `.SymLogNorm`.
#
# Note that colorbar labels do not come out looking very good.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (5 * Z1 - Z2) * 2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=colors.SymLogNorm(linthresh=0.015,
vmin=-10.0, vmax=10.0, base=10))
fig.colorbar(pcm, ax=ax[1], extend='both', label='SymLogNorm')
# %%
# Custom Norm
# -----------
# Alternatively, the above example data can be scaled with a customized normalization.
# This one normalizes the negative data differently from the positive.
# Example of making your own norm. Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
super().__init__(vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
# %%
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=MidpointNormalize(midpoint=0))
fig.colorbar(pcm, ax=ax[1], extend='both', label='Custom norm')
# %%
# BoundaryNorm
# ------------
# For arbitrarily dividing the color scale, the `.BoundaryNorm` may be used; by
# providing the boundaries for colors, this norm puts the first color in between the
# first pair, the second color between the second pair, etc.
fig, ax = plt.subplots(3, 1, layout='constrained')
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical',
label='linear scaling')
# Evenly-spaced bounds gives a contour-like effect.
bounds = np.linspace(-2, 2, 11)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical',
label='BoundaryNorm\nlinspace(-2, 2, 11)')
# Unevenly-spaced bounds changes the colormapping.
bounds = np.array([-1, -0.5, 0, 2.5, 5])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical',
label='BoundaryNorm\n[-1, -0.5, 0, 2.5, 5]')
plt.show()
| stable__gallery__images_contours_and_fields__colormap_normalizations | 3 | figure_003.png | Colormap normalizations — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/colormap_normalizations.html#symlognorm | https://matplotlib.org/stable/_downloads/7246e4cd4f0a538ca175e2afddd49c5e/colormap_normalizations.py | colormap_normalizations.py | images_contours_and_fields | ok | 5 | null | |
"""
=======================
Colormap normalizations
=======================
Demonstration of using norm to map colormaps onto data in non-linear ways.
.. redirect-from:: /gallery/userdemo/colormap_normalizations
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
N = 100
# %%
# LogNorm
# -------
# This example data has a low hump with a spike coming out of its center. If plotted
# using a linear colour scale, then only the spike will be visible. To see both hump and
# spike, this requires the z/colour axis on a log scale.
#
# Instead of transforming the data with ``pcolor(log10(Z))``, the color mapping can be
# made logarithmic using a `.LogNorm`.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()))
fig.colorbar(pcm, ax=ax[1], extend='max', label='LogNorm')
# %%
# PowerNorm
# ---------
# This example data mixes a power-law trend in X with a rectified sine wave in Y. If
# plotted using a linear colour scale, then the power-law trend in X partially obscures
# the sine wave in Y.
#
# The power law can be removed using a `.PowerNorm`.
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z = (1 + np.sin(Y * 10)) * X**2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest')
fig.colorbar(pcm, ax=ax[0], extend='max', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='PuBu_r', shading='nearest',
norm=colors.PowerNorm(gamma=0.5))
fig.colorbar(pcm, ax=ax[1], extend='max', label='PowerNorm')
# %%
# SymLogNorm
# ----------
# This example data has two humps, one negative and one positive, The positive hump has
# 5 times the amplitude of the negative. If plotted with a linear colour scale, then
# the detail in the negative hump is obscured.
#
# Here we logarithmically scale the positive and negative data separately with
# `.SymLogNorm`.
#
# Note that colorbar labels do not come out looking very good.
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (5 * Z1 - Z2) * 2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=colors.SymLogNorm(linthresh=0.015,
vmin=-10.0, vmax=10.0, base=10))
fig.colorbar(pcm, ax=ax[1], extend='both', label='SymLogNorm')
# %%
# Custom Norm
# -----------
# Alternatively, the above example data can be scaled with a customized normalization.
# This one normalizes the negative data differently from the positive.
# Example of making your own norm. Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
super().__init__(vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
# %%
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', label='linear scaling')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=MidpointNormalize(midpoint=0))
fig.colorbar(pcm, ax=ax[1], extend='both', label='Custom norm')
# %%
# BoundaryNorm
# ------------
# For arbitrarily dividing the color scale, the `.BoundaryNorm` may be used; by
# providing the boundaries for colors, this norm puts the first color in between the
# first pair, the second color between the second pair, etc.
fig, ax = plt.subplots(3, 1, layout='constrained')
pcm = ax[0].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical',
label='linear scaling')
# Evenly-spaced bounds gives a contour-like effect.
bounds = np.linspace(-2, 2, 11)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical',
label='BoundaryNorm\nlinspace(-2, 2, 11)')
# Unevenly-spaced bounds changes the colormapping.
bounds = np.array([-1, -0.5, 0, 2.5, 5])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', shading='nearest',
norm=norm)
fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical',
label='BoundaryNorm\n[-1, -0.5, 0, 2.5, 5]')
plt.show()
| stable__gallery__images_contours_and_fields__colormap_normalizations | 4 | figure_004.png | Colormap normalizations — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/colormap_normalizations.html#symlognorm | https://matplotlib.org/stable/_downloads/7246e4cd4f0a538ca175e2afddd49c5e/colormap_normalizations.py | colormap_normalizations.py | images_contours_and_fields | ok | 5 | null | |
"""
==================================
Colormap normalizations SymLogNorm
==================================
Demonstration of using norm to map colormaps onto data in non-linear ways.
.. redirect-from:: /gallery/userdemo/colormap_normalization_symlognorm
"""
# %%
# Synthetic dataset consisting of two humps, one negative and one positive,
# the positive with 8-times the amplitude.
# Linearly, the negative hump is almost invisible,
# and it is very difficult to see any detail of its profile.
# With the logarithmic scaling applied to both positive and negative values,
# it is much easier to see the shape of each hump.
#
# See `~.colors.SymLogNorm`.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
def rbf(x, y):
return 1.0 / (1 + 5 * ((x ** 2) + (y ** 2)))
N = 200
gain = 8
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = rbf(X + 0.5, Y + 0.5)
Z2 = rbf(X - 0.5, Y - 0.5)
Z = gain * Z1 - Z2
shadeopts = {'cmap': 'PRGn', 'shading': 'gouraud'}
colormap = 'PRGn'
lnrwidth = 0.5
fig, ax = plt.subplots(2, 1, sharex=True, sharey=True)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=lnrwidth, linscale=1,
vmin=-gain, vmax=gain, base=10),
**shadeopts)
fig.colorbar(pcm, ax=ax[0], extend='both')
ax[0].text(-2.5, 1.5, 'symlog')
pcm = ax[1].pcolormesh(X, Y, Z, vmin=-gain, vmax=gain,
**shadeopts)
fig.colorbar(pcm, ax=ax[1], extend='both')
ax[1].text(-2.5, 1.5, 'linear')
# %%
# In order to find the best visualization for any particular dataset,
# it may be necessary to experiment with multiple different color scales.
# As well as the `~.colors.SymLogNorm` scaling, there is also
# the option of using `~.colors.AsinhNorm` (experimental), which has a smoother
# transition between the linear and logarithmic regions of the transformation
# applied to the data values, "Z".
# In the plots below, it may be possible to see contour-like artifacts
# around each hump despite there being no sharp features
# in the dataset itself. The ``asinh`` scaling shows a smoother shading
# of each hump.
fig, ax = plt.subplots(2, 1, sharex=True, sharey=True)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=lnrwidth, linscale=1,
vmin=-gain, vmax=gain, base=10),
**shadeopts)
fig.colorbar(pcm, ax=ax[0], extend='both')
ax[0].text(-2.5, 1.5, 'symlog')
pcm = ax[1].pcolormesh(X, Y, Z,
norm=colors.AsinhNorm(linear_width=lnrwidth,
vmin=-gain, vmax=gain),
**shadeopts)
fig.colorbar(pcm, ax=ax[1], extend='both')
ax[1].text(-2.5, 1.5, 'asinh')
plt.show()
| stable__gallery__images_contours_and_fields__colormap_normalizations_symlognorm | 0 | figure_000.png | Colormap normalizations SymLogNorm — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/colormap_normalizations_symlognorm.html#sphx-glr-download-gallery-images-contours-and-fields-colormap-normalizations-symlognorm-py | https://matplotlib.org/stable/_downloads/add263170379d71b432151cf853a3c0d/colormap_normalizations_symlognorm.py | colormap_normalizations_symlognorm.py | images_contours_and_fields | ok | 2 | null | |
"""
==================================
Colormap normalizations SymLogNorm
==================================
Demonstration of using norm to map colormaps onto data in non-linear ways.
.. redirect-from:: /gallery/userdemo/colormap_normalization_symlognorm
"""
# %%
# Synthetic dataset consisting of two humps, one negative and one positive,
# the positive with 8-times the amplitude.
# Linearly, the negative hump is almost invisible,
# and it is very difficult to see any detail of its profile.
# With the logarithmic scaling applied to both positive and negative values,
# it is much easier to see the shape of each hump.
#
# See `~.colors.SymLogNorm`.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
def rbf(x, y):
return 1.0 / (1 + 5 * ((x ** 2) + (y ** 2)))
N = 200
gain = 8
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = rbf(X + 0.5, Y + 0.5)
Z2 = rbf(X - 0.5, Y - 0.5)
Z = gain * Z1 - Z2
shadeopts = {'cmap': 'PRGn', 'shading': 'gouraud'}
colormap = 'PRGn'
lnrwidth = 0.5
fig, ax = plt.subplots(2, 1, sharex=True, sharey=True)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=lnrwidth, linscale=1,
vmin=-gain, vmax=gain, base=10),
**shadeopts)
fig.colorbar(pcm, ax=ax[0], extend='both')
ax[0].text(-2.5, 1.5, 'symlog')
pcm = ax[1].pcolormesh(X, Y, Z, vmin=-gain, vmax=gain,
**shadeopts)
fig.colorbar(pcm, ax=ax[1], extend='both')
ax[1].text(-2.5, 1.5, 'linear')
# %%
# In order to find the best visualization for any particular dataset,
# it may be necessary to experiment with multiple different color scales.
# As well as the `~.colors.SymLogNorm` scaling, there is also
# the option of using `~.colors.AsinhNorm` (experimental), which has a smoother
# transition between the linear and logarithmic regions of the transformation
# applied to the data values, "Z".
# In the plots below, it may be possible to see contour-like artifacts
# around each hump despite there being no sharp features
# in the dataset itself. The ``asinh`` scaling shows a smoother shading
# of each hump.
fig, ax = plt.subplots(2, 1, sharex=True, sharey=True)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=lnrwidth, linscale=1,
vmin=-gain, vmax=gain, base=10),
**shadeopts)
fig.colorbar(pcm, ax=ax[0], extend='both')
ax[0].text(-2.5, 1.5, 'symlog')
pcm = ax[1].pcolormesh(X, Y, Z,
norm=colors.AsinhNorm(linear_width=lnrwidth,
vmin=-gain, vmax=gain),
**shadeopts)
fig.colorbar(pcm, ax=ax[1], extend='both')
ax[1].text(-2.5, 1.5, 'asinh')
plt.show()
| stable__gallery__images_contours_and_fields__colormap_normalizations_symlognorm | 1 | figure_001.png | Colormap normalizations SymLogNorm — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/images_contours_and_fields/colormap_normalizations_symlognorm.html#sphx-glr-download-gallery-images-contours-and-fields-colormap-normalizations-symlognorm-py | https://matplotlib.org/stable/_downloads/add263170379d71b432151cf853a3c0d/colormap_normalizations_symlognorm.py | colormap_normalizations_symlognorm.py | images_contours_and_fields | ok | 2 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.