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 |
Matplotlib Code-Image Pairs
Dataset Summary
This dataset contains static Matplotlib figure images paired with the Python source code that generated them. It was built from the official Matplotlib gallery and excludes animation-style examples. Each row corresponds to one rendered image. Examples that produce multiple figures contribute multiple rows.
Dataset Composition
- Image/code rows: 643
- Source examples: 452
- Examples with multiple figures: 74
- Included statuses: ok
- Source gallery: https://matplotlib.org/stable/gallery/index.html
Top Categories
lines_bars_and_markers: 48 examplesimages_contours_and_fields: 47 examplestext_labels_and_annotations: 46 examplesmplot3d: 44 examplessubplots_axes_and_figures: 35 examplesmisc: 25 examplesticks: 24 examplesaxes_grid1: 22 examplesstatistics: 21 examplesevent_handling: 20 examples
Row Schema
image: rendered PNG for one figurecode: full Python source for the exampleexample_id: stable identifier derived from the Matplotlib gallery URLfigure_index: zero-based figure index within the examplefigure_name: original rendered image filenametitle: example page titleexample_page_url: Matplotlib gallery page URLsource_url: downloadable Python source URL when availablesource_relpath: source filename reported by the scrapercategory_hint: rough gallery category inferred from the URL pathstatus: scraper/render status kept for provenancenum_figures: number of figures reported for the source exampleerror: render or scrape error text, usually null for successful rows
Build Process
- Crawl the official Matplotlib gallery.
- Download the Python source for each example page.
- Render examples with Matplotlib's non-interactive
Aggbackend. - Keep static rendered image/code pairs and skip dynamic animation-style examples.
- Export one dataset row per rendered image.
Usage
Load the local saved dataset:
from datasets import load_from_disk
ds = load_from_disk("/usr/project/xtmp/ap843/hf_datasets/matplotlib_code_image_pairs")["train"]
Load from the Hugging Face Hub after pushing:
from datasets import load_dataset
ds = load_dataset("ajayvikram/matplotlib-code-image", split="train")
License And Attribution
This dataset is derived from Matplotlib gallery examples. The card metadata uses license: other with
license_name: matplotlib-license and license_link: https://matplotlib.org/stable/project/license.html because the Matplotlib project uses a
project-specific license rather than a standard Hugging Face license identifier. The official Matplotlib license
permits use, distribution, and derivative works provided the Matplotlib copyright notice and license agreement
are retained. This is an interpretation of the official license page, not legal advice.
- Downloads last month
- 24