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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
"""
===============================
Fill the area between two lines
===============================
This example shows how to use `~.axes.Axes.fill_between` to color the area
between two lines.
"""
import matplotlib.pyplot as plt
import numpy as np
# %%
#
# Basic usage
# -----------
# The parameters *y1* and *y2* can be scalars, indicating a horizontal
# boundary at the given y-values. If only *y1* is given, *y2* defaults to 0.
x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)
y2 = 0.8 * np.sin(4 * np.pi * x)
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(6, 6))
ax1.fill_between(x, y1)
ax1.set_title('fill between y1 and 0')
ax2.fill_between(x, y1, 1)
ax2.set_title('fill between y1 and 1')
ax3.fill_between(x, y1, y2)
ax3.set_title('fill between y1 and y2')
ax3.set_xlabel('x')
fig.tight_layout()
# %%
#
# Example: Confidence bands
# -------------------------
# A common application for `~.axes.Axes.fill_between` is the indication of
# confidence bands.
#
# `~.axes.Axes.fill_between` uses the colors of the color cycle as the fill
# color. These may be a bit strong when applied to fill areas. It is
# therefore often a good practice to lighten the color by making the area
# semi-transparent using *alpha*.
# sphinx_gallery_thumbnail_number = 2
N = 21
x = np.linspace(0, 10, 11)
y = [3.9, 4.4, 10.8, 10.3, 11.2, 13.1, 14.1, 9.9, 13.9, 15.1, 12.5]
# fit a linear curve and estimate its y-values and their error.
a, b = np.polyfit(x, y, deg=1)
y_est = a * x + b
y_err = x.std() * np.sqrt(1/len(x) +
(x - x.mean())**2 / np.sum((x - x.mean())**2))
fig, ax = plt.subplots()
ax.plot(x, y_est, '-')
ax.fill_between(x, y_est - y_err, y_est + y_err, alpha=0.2)
ax.plot(x, y, 'o', color='tab:brown')
# %%
#
# Selectively filling horizontal regions
# --------------------------------------
# The parameter *where* allows to specify the x-ranges to fill. It's a boolean
# array with the same size as *x*.
#
# Only x-ranges of contiguous *True* sequences are filled. As a result the
# range between neighboring *True* and *False* values is never filled. This
# often undesired when the data points should represent a contiguous quantity.
# It is therefore recommended to set ``interpolate=True`` unless the
# x-distance of the data points is fine enough so that the above effect is not
# noticeable. Interpolation approximates the actual x position at which the
# *where* condition will change and extends the filling up to there.
x = np.array([0, 1, 2, 3])
y1 = np.array([0.8, 0.8, 0.2, 0.2])
y2 = np.array([0, 0, 1, 1])
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.set_title('interpolation=False')
ax1.plot(x, y1, 'o--')
ax1.plot(x, y2, 'o--')
ax1.fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3)
ax1.fill_between(x, y1, y2, where=(y1 < y2), color='C1', alpha=0.3)
ax2.set_title('interpolation=True')
ax2.plot(x, y1, 'o--')
ax2.plot(x, y2, 'o--')
ax2.fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3,
interpolate=True)
ax2.fill_between(x, y1, y2, where=(y1 <= y2), color='C1', alpha=0.3,
interpolate=True)
fig.tight_layout()
# %%
#
# .. note::
#
# Similar gaps will occur if *y1* or *y2* are masked arrays. Since missing
# values cannot be approximated, *interpolate* has no effect in this case.
# The gaps around masked values can only be reduced by adding more data
# points close to the masked values.
# %%
#
# Selectively marking horizontal regions across the whole Axes
# ------------------------------------------------------------
# The same selection mechanism can be applied to fill the full vertical height
# of the Axes. To be independent of y-limits, we add a transform that
# interprets the x-values in data coordinates and the y-values in Axes
# coordinates.
#
# The following example marks the regions in which the y-data are above a
# given threshold.
fig, ax = plt.subplots()
x = np.arange(0, 4 * np.pi, 0.01)
y = np.sin(x)
ax.plot(x, y, color='black')
threshold = 0.75
ax.axhline(threshold, color='green', lw=2, alpha=0.7)
ax.fill_between(x, 0, 1, where=y > threshold,
color='green', alpha=0.5, transform=ax.get_xaxis_transform())
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.fill_between` / `matplotlib.pyplot.fill_between`
# - `matplotlib.axes.Axes.get_xaxis_transform`
#
# .. tags::
#
# styling: conditional
# plot-type: fill_between
# level: beginner
# purpose: showcase
| stable__gallery__lines_bars_and_markers__fill_between_demo | 3 | figure_003.png | Fill the area between two lines — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/fill_between_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-fill-between-demo-py | https://matplotlib.org/stable/_downloads/264a8be4de96930763e780682bdaba2d/fill_between_demo.py | fill_between_demo.py | lines_bars_and_markers | ok | 4 | null | |
"""
========================================
Fill the area between two vertical lines
========================================
Using `~.Axes.fill_betweenx` to color along the horizontal direction between
two curves.
"""
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)
fig, [ax1, ax2, ax3] = plt.subplots(1, 3, sharey=True, figsize=(6, 6))
ax1.fill_betweenx(y, 0, x1)
ax1.set_title('between (x1, 0)')
ax2.fill_betweenx(y, x1, 1)
ax2.set_title('between (x1, 1)')
ax2.set_xlabel('x')
ax3.fill_betweenx(y, x1, x2)
ax3.set_title('between (x1, x2)')
# %%
# Now fill between x1 and x2 where a logical condition is met. Note this is
# different than calling::
#
# fill_between(y[where], x1[where], x2[where])
#
# because of edge effects over multiple contiguous regions.
fig, [ax, ax1] = plt.subplots(1, 2, sharey=True, figsize=(6, 6))
ax.plot(x1, y, x2, y, color='black')
ax.fill_betweenx(y, x1, x2, where=x2 >= x1, facecolor='green')
ax.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='red')
ax.set_title('fill_betweenx where')
# Test support for masked arrays.
x2 = np.ma.masked_greater(x2, 1.0)
ax1.plot(x1, y, x2, y, color='black')
ax1.fill_betweenx(y, x1, x2, where=x2 >= x1, facecolor='green')
ax1.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='red')
ax1.set_title('regions with x2 > 1 are masked')
# %%
# This example illustrates a problem; because of the data gridding, there are
# undesired unfilled triangles at the crossover points. A brute-force solution
# would be to interpolate all arrays to a very fine grid before plotting.
plt.show()
# %%
# .. tags::
#
# plot-type: fill_between
# level: beginner
| stable__gallery__lines_bars_and_markers__fill_betweenx_demo | 0 | figure_000.png | Fill the area between two vertical lines — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/fill_betweenx_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-fill-betweenx-demo-py | https://matplotlib.org/stable/_downloads/25520da3172b0ab1766f2f0bd31a49f6/fill_betweenx_demo.py | fill_betweenx_demo.py | lines_bars_and_markers | ok | 2 | null | |
"""
========================================
Fill the area between two vertical lines
========================================
Using `~.Axes.fill_betweenx` to color along the horizontal direction between
two curves.
"""
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)
fig, [ax1, ax2, ax3] = plt.subplots(1, 3, sharey=True, figsize=(6, 6))
ax1.fill_betweenx(y, 0, x1)
ax1.set_title('between (x1, 0)')
ax2.fill_betweenx(y, x1, 1)
ax2.set_title('between (x1, 1)')
ax2.set_xlabel('x')
ax3.fill_betweenx(y, x1, x2)
ax3.set_title('between (x1, x2)')
# %%
# Now fill between x1 and x2 where a logical condition is met. Note this is
# different than calling::
#
# fill_between(y[where], x1[where], x2[where])
#
# because of edge effects over multiple contiguous regions.
fig, [ax, ax1] = plt.subplots(1, 2, sharey=True, figsize=(6, 6))
ax.plot(x1, y, x2, y, color='black')
ax.fill_betweenx(y, x1, x2, where=x2 >= x1, facecolor='green')
ax.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='red')
ax.set_title('fill_betweenx where')
# Test support for masked arrays.
x2 = np.ma.masked_greater(x2, 1.0)
ax1.plot(x1, y, x2, y, color='black')
ax1.fill_betweenx(y, x1, x2, where=x2 >= x1, facecolor='green')
ax1.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='red')
ax1.set_title('regions with x2 > 1 are masked')
# %%
# This example illustrates a problem; because of the data gridding, there are
# undesired unfilled triangles at the crossover points. A brute-force solution
# would be to interpolate all arrays to a very fine grid before plotting.
plt.show()
# %%
# .. tags::
#
# plot-type: fill_between
# level: beginner
| stable__gallery__lines_bars_and_markers__fill_betweenx_demo | 1 | figure_001.png | Fill the area between two vertical lines — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/fill_betweenx_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-fill-betweenx-demo-py | https://matplotlib.org/stable/_downloads/25520da3172b0ab1766f2f0bd31a49f6/fill_betweenx_demo.py | fill_betweenx_demo.py | lines_bars_and_markers | ok | 2 | null | |
"""
========================
Bar chart with gradients
========================
Matplotlib does not natively support gradients. However, we can emulate a
gradient-filled rectangle by an `.AxesImage` of the right size and coloring.
In particular, we use a colormap to generate the actual colors. It is then
sufficient to define the underlying values on the corners of the image and
let bicubic interpolation fill out the area. We define the gradient direction
by a unit vector *v*. The values at the corners are then obtained by the
lengths of the projections of the corner vectors on *v*.
A similar approach can be used to create a gradient background for an Axes.
In that case, it is helpful to use Axes coordinates (``extent=(0, 1, 0, 1),
transform=ax.transAxes``) to be independent of the data coordinates.
"""
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
def gradient_image(ax, direction=0.3, cmap_range=(0, 1), **kwargs):
"""
Draw a gradient image based on a colormap.
Parameters
----------
ax : Axes
The Axes to draw on.
direction : float
The direction of the gradient. This is a number in
range 0 (=vertical) to 1 (=horizontal).
cmap_range : float, float
The fraction (cmin, cmax) of the colormap that should be
used for the gradient, where the complete colormap is (0, 1).
**kwargs
Other parameters are passed on to `.Axes.imshow()`.
In particular, *cmap*, *extent*, and *transform* may be useful.
"""
phi = direction * np.pi / 2
v = np.array([np.cos(phi), np.sin(phi)])
X = np.array([[v @ [1, 0], v @ [1, 1]],
[v @ [0, 0], v @ [0, 1]]])
a, b = cmap_range
X = a + (b - a) / X.max() * X
im = ax.imshow(X, interpolation='bicubic', clim=(0, 1),
aspect='auto', **kwargs)
return im
def gradient_bar(ax, x, y, width=0.5, bottom=0):
for left, top in zip(x, y):
right = left + width
gradient_image(ax, extent=(left, right, bottom, top),
cmap=plt.cm.Blues_r, cmap_range=(0, 0.8))
fig, ax = plt.subplots()
ax.set(xlim=(0, 10), ylim=(0, 1))
# background image
gradient_image(ax, direction=1, extent=(0, 1, 0, 1), transform=ax.transAxes,
cmap=plt.cm.RdYlGn, cmap_range=(0.2, 0.8), alpha=0.5)
N = 10
x = np.arange(N) + 0.15
y = np.random.rand(N)
gradient_bar(ax, x, y, width=0.7)
plt.show()
# %%
# .. tags::
#
# styling: color
# plot-type: imshow
# level: intermediate
# purpose: showcase
| stable__gallery__lines_bars_and_markers__gradient_bar | 0 | figure_000.png | Bar chart with gradients — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/gradient_bar.html#sphx-glr-download-gallery-lines-bars-and-markers-gradient-bar-py | https://matplotlib.org/stable/_downloads/e83fa918d4012d4ca7e2bd48e7ab0935/gradient_bar.py | gradient_bar.py | lines_bars_and_markers | ok | 1 | null | |
"""
=========
Hat graph
=========
This example shows how to create a `hat graph`_ and how to annotate it with
labels.
.. _hat graph: https://doi.org/10.1186/s41235-019-0182-3
"""
import matplotlib.pyplot as plt
import numpy as np
def hat_graph(ax, xlabels, values, group_labels):
"""
Create a hat graph.
Parameters
----------
ax : matplotlib.axes.Axes
The Axes to plot into.
xlabels : list of str
The category names to be displayed on the x-axis.
values : (M, N) array-like
The data values.
Rows are the groups (len(group_labels) == M).
Columns are the categories (len(xlabels) == N).
group_labels : list of str
The group labels displayed in the legend.
"""
def label_bars(heights, rects):
"""Attach a text label on top of each bar."""
for height, rect in zip(heights, rects):
ax.annotate(f'{height}',
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 4), # 4 points vertical offset.
textcoords='offset points',
ha='center', va='bottom')
values = np.asarray(values)
x = np.arange(values.shape[1])
ax.set_xticks(x, labels=xlabels)
spacing = 0.3 # spacing between hat groups
width = (1 - spacing) / values.shape[0]
heights0 = values[0]
for i, (heights, group_label) in enumerate(zip(values, group_labels)):
style = {'fill': False} if i == 0 else {'edgecolor': 'black'}
rects = ax.bar(x - spacing/2 + i * width, heights - heights0,
width, bottom=heights0, label=group_label, **style)
label_bars(heights, rects)
# initialise labels and a numpy array make sure you have
# N labels of N number of values in the array
xlabels = ['I', 'II', 'III', 'IV', 'V']
playerA = np.array([5, 15, 22, 20, 25])
playerB = np.array([25, 32, 34, 30, 27])
fig, ax = plt.subplots()
hat_graph(ax, xlabels, [playerA, playerB], ['Player A', 'Player B'])
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xlabel('Games')
ax.set_ylabel('Score')
ax.set_ylim(0, 60)
ax.set_title('Scores by number of game and players')
ax.legend()
fig.tight_layout()
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.bar`
# - `matplotlib.axes.Axes.annotate` / `matplotlib.pyplot.annotate`
#
# .. tags::
#
# component: annotate
# plot-type: bar
# level: beginner
| stable__gallery__lines_bars_and_markers__hat_graph | 0 | figure_000.png | Hat graph — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/hat_graph.html#sphx-glr-download-gallery-lines-bars-and-markers-hat-graph-py | https://matplotlib.org/stable/_downloads/ff9b887ec7665e75d3992d3af408be52/hat_graph.py | hat_graph.py | lines_bars_and_markers | ok | 1 | null | |
"""
=============================================
Discrete distribution as horizontal bar chart
=============================================
Stacked bar charts can be used to visualize discrete distributions.
This example visualizes the result of a survey in which people could rate
their agreement to questions on a five-element scale.
The horizontal stacking is achieved by calling `~.Axes.barh()` for each
category and passing the starting point as the cumulative sum of the
already drawn bars via the parameter ``left``.
"""
import matplotlib.pyplot as plt
import numpy as np
category_names = ['Strongly disagree', 'Disagree',
'Neither agree nor disagree', 'Agree', 'Strongly agree']
results = {
'Question 1': [10, 15, 17, 32, 26],
'Question 2': [26, 22, 29, 10, 13],
'Question 3': [35, 37, 7, 2, 19],
'Question 4': [32, 11, 9, 15, 33],
'Question 5': [21, 29, 5, 5, 40],
'Question 6': [8, 19, 5, 30, 38]
}
def survey(results, category_names):
"""
Parameters
----------
results : dict
A mapping from question labels to a list of answers per category.
It is assumed all lists contain the same number of entries and that
it matches the length of *category_names*.
category_names : list of str
The category labels.
"""
labels = list(results.keys())
data = np.array(list(results.values()))
data_cum = data.cumsum(axis=1)
category_colors = plt.colormaps['RdYlGn'](
np.linspace(0.15, 0.85, data.shape[1]))
fig, ax = plt.subplots(figsize=(9.2, 5))
ax.invert_yaxis()
ax.xaxis.set_visible(False)
ax.set_xlim(0, np.sum(data, axis=1).max())
for i, (colname, color) in enumerate(zip(category_names, category_colors)):
widths = data[:, i]
starts = data_cum[:, i] - widths
rects = ax.barh(labels, widths, left=starts, height=0.5,
label=colname, color=color)
r, g, b, _ = color
text_color = 'white' if r * g * b < 0.5 else 'darkgrey'
ax.bar_label(rects, label_type='center', color=text_color)
ax.legend(ncols=len(category_names), bbox_to_anchor=(0, 1),
loc='lower left', fontsize='small')
return fig, ax
survey(results, category_names)
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.barh` / `matplotlib.pyplot.barh`
# - `matplotlib.axes.Axes.bar_label` / `matplotlib.pyplot.bar_label`
# - `matplotlib.axes.Axes.legend` / `matplotlib.pyplot.legend`
#
# .. tags::
#
# domain: statistics
# component: label
# plot-type: bar
# level: beginner
| stable__gallery__lines_bars_and_markers__horizontal_barchart_distribution | 0 | figure_000.png | Discrete distribution as horizontal bar chart — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/horizontal_barchart_distribution.html#sphx-glr-download-gallery-lines-bars-and-markers-horizontal-barchart-distribution-py | https://matplotlib.org/stable/_downloads/77d0d6c2d02582d80df43b9b9e78610c/horizontal_barchart_distribution.py | horizontal_barchart_distribution.py | lines_bars_and_markers | ok | 1 | null | |
"""
=========
JoinStyle
=========
The `matplotlib._enums.JoinStyle` controls how Matplotlib draws the corners
where two different line segments meet. For more details, see the
`~matplotlib._enums.JoinStyle` docs.
"""
import matplotlib.pyplot as plt
from matplotlib._enums import JoinStyle
JoinStyle.demo()
plt.show()
# %%
# .. tags:: purpose: reference, styling: linestyle
| stable__gallery__lines_bars_and_markers__joinstyle | 0 | figure_000.png | JoinStyle — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/joinstyle.html#sphx-glr-download-gallery-lines-bars-and-markers-joinstyle-py | https://matplotlib.org/stable/_downloads/6bb713e635f8898fbc28683331020d84/joinstyle.py | joinstyle.py | lines_bars_and_markers | ok | 1 | null | |
"""
===============================
Dashed line style configuration
===============================
The dashing of a line is controlled via a dash sequence. It can be modified
using `.Line2D.set_dashes`.
The dash sequence is a series of on/off lengths in points, e.g.
``[3, 1]`` would be 3pt long lines separated by 1pt spaces.
Some functions like `.Axes.plot` support passing Line properties as keyword
arguments. In such a case, you can already set the dashing when creating the
line.
*Note*: The dash style can also be configured via a
:ref:`property_cycle <color_cycle>`
by passing a list of dash sequences using the keyword *dashes* to the
cycler. This is not shown within this example.
Other attributes of the dash may also be set either with the relevant method
(`~.Line2D.set_dash_capstyle`, `~.Line2D.set_dash_joinstyle`,
`~.Line2D.set_gapcolor`) or by passing the property through a plotting
function.
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 500)
y = np.sin(x)
plt.rc('lines', linewidth=2.5)
fig, ax = plt.subplots()
# Using set_dashes() and set_capstyle() to modify dashing of an existing line.
line1, = ax.plot(x, y, label='Using set_dashes() and set_dash_capstyle()')
line1.set_dashes([2, 2, 10, 2]) # 2pt line, 2pt break, 10pt line, 2pt break.
line1.set_dash_capstyle('round')
# Using plot(..., dashes=...) to set the dashing when creating a line.
line2, = ax.plot(x, y - 0.2, dashes=[6, 2], label='Using the dashes parameter')
# Using plot(..., dashes=..., gapcolor=...) to set the dashing and
# alternating color when creating a line.
line3, = ax.plot(x, y - 0.4, dashes=[4, 4], gapcolor='tab:pink',
label='Using the dashes and gapcolor parameters')
ax.legend(handlelength=4)
plt.show()
# %%
# .. tags::
#
# styling: linestyle
# plot-style: line
# level: beginner
| stable__gallery__lines_bars_and_markers__line_demo_dash_control | 0 | figure_000.png | Dashed line style configuration — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/line_demo_dash_control.html#sphx-glr-download-gallery-lines-bars-and-markers-line-demo-dash-control-py | https://matplotlib.org/stable/_downloads/1c02700bb13e6571e774c10ba73db267/line_demo_dash_control.py | line_demo_dash_control.py | lines_bars_and_markers | ok | 1 | null | |
"""
==============================
Lines with a ticked patheffect
==============================
Ticks can be added along a line to mark one side as a barrier using
`~matplotlib.patheffects.TickedStroke`. You can control the angle,
spacing, and length of the ticks.
The ticks will also appear appropriately in the legend.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patheffects
# Plot a straight diagonal line with ticked style path
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot([0, 1], [0, 1], label="Line",
path_effects=[patheffects.withTickedStroke(spacing=7, angle=135)])
# Plot a curved line with ticked style path
nx = 101
x = np.linspace(0.0, 1.0, nx)
y = 0.3*np.sin(x*8) + 0.4
ax.plot(x, y, label="Curve", path_effects=[patheffects.withTickedStroke()])
ax.legend()
plt.show()
# %%
# .. tags::
#
# styling: linestyle
# plot-type: line
# level: beginner
| stable__gallery__lines_bars_and_markers__lines_with_ticks_demo | 0 | figure_000.png | Lines with a ticked patheffect — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/lines_with_ticks_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-lines-with-ticks-demo-py | https://matplotlib.org/stable/_downloads/3269caad4b186ff2ba73f725b2cb5a12/lines_with_ticks_demo.py | lines_with_ticks_demo.py | lines_bars_and_markers | ok | 1 | null | |
"""
==========
Linestyles
==========
Simple linestyles can be defined using the strings "solid", "dotted", "dashed"
or "dashdot". More refined control can be achieved by providing a dash tuple
``(offset, (on_off_seq))``. For example, ``(0, (3, 10, 1, 15))`` means
(3pt line, 10pt space, 1pt line, 15pt space) with no offset, while
``(5, (10, 3))``, means (10pt line, 3pt space), but skip the first 5pt line.
See also `.Line2D.set_linestyle`. The specific on/off sequences of the
"dotted", "dashed" and "dashdot" styles are configurable:
* :rc:`lines.dotted_pattern`
* :rc:`lines.dashed_pattern`
* :rc:`lines.dashdot_pattern`
*Note*: The dash style can also be configured via `.Line2D.set_dashes`
as shown in :doc:`/gallery/lines_bars_and_markers/line_demo_dash_control`
and passing a list of dash sequences using the keyword *dashes* to the
cycler in :ref:`property_cycle <color_cycle>`.
"""
import matplotlib.pyplot as plt
import numpy as np
linestyle_str = [
('solid', 'solid'), # Same as (0, ()) or '-'
('dotted', 'dotted'), # Same as ':'
('dashed', 'dashed'), # Same as '--'
('dashdot', 'dashdot')] # Same as '-.'
linestyle_tuple = [
('loosely dotted', (0, (1, 10))),
('dotted', (0, (1, 5))),
('densely dotted', (0, (1, 1))),
('long dash with offset', (5, (10, 3))),
('loosely dashed', (0, (5, 10))),
('dashed', (0, (5, 5))),
('densely dashed', (0, (5, 1))),
('loosely dashdotted', (0, (3, 10, 1, 10))),
('dashdotted', (0, (3, 5, 1, 5))),
('densely dashdotted', (0, (3, 1, 1, 1))),
('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),
('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))]
def plot_linestyles(ax, linestyles, title):
X, Y = np.linspace(0, 100, 10), np.zeros(10)
yticklabels = []
for i, (name, linestyle) in enumerate(linestyles):
ax.plot(X, Y+i, linestyle=linestyle, linewidth=1.5, color='black')
yticklabels.append(name)
ax.set_title(title)
ax.set(ylim=(-0.5, len(linestyles)-0.5),
yticks=np.arange(len(linestyles)),
yticklabels=yticklabels)
ax.tick_params(left=False, bottom=False, labelbottom=False)
ax.spines[:].set_visible(False)
# For each line style, add a text annotation with a small offset from
# the reference point (0 in Axes coords, y tick value in Data coords).
for i, (name, linestyle) in enumerate(linestyles):
ax.annotate(repr(linestyle),
xy=(0.0, i), xycoords=ax.get_yaxis_transform(),
xytext=(-6, -12), textcoords='offset points',
color="blue", fontsize=8, ha="right", family="monospace")
fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(7, 8), height_ratios=[1, 3],
layout='constrained')
plot_linestyles(ax0, linestyle_str[::-1], title='Named linestyles')
plot_linestyles(ax1, linestyle_tuple[::-1], title='Parametrized linestyles')
plt.show()
# %%
# .. tags::
#
# styling: linestyle
# purpose: reference
| stable__gallery__lines_bars_and_markers__linestyles | 0 | figure_000.png | Linestyles — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html#sphx-glr-download-gallery-lines-bars-and-markers-linestyles-py | https://matplotlib.org/stable/_downloads/79cca01aa25ff65b23b051f7e4ca55f5/linestyles.py | linestyles.py | lines_bars_and_markers | ok | 1 | null | |
"""
================
Marker reference
================
Matplotlib supports multiple categories of markers which are selected using
the ``marker`` parameter of plot commands:
- `Unfilled markers`_
- `Filled markers`_
- `Markers created from TeX symbols`_
- `Markers created from Paths`_
For a list of all markers see also the `matplotlib.markers` documentation.
For example usages see
:doc:`/gallery/lines_bars_and_markers/scatter_star_poly`.
.. redirect-from:: /gallery/shapes_and_collections/marker_path
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
# %%
# Unfilled markers
# ================
# Unfilled markers are single-colored.
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Filled markers
# ==============
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# .. _marker_fill_styles:
#
# Marker fill styles
# ------------------
# The edge color and fill color of filled markers can be specified separately.
# Additionally, the ``fillstyle`` can be configured to be unfilled, fully
# filled, or half-filled in various directions. The half-filled styles use
# ``markerfacecoloralt`` as secondary fill color.
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
# %%
# Markers created from TeX symbols
# ================================
#
# Use :ref:`MathText <mathtext>`, to use custom marker symbols,
# like e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer
# to the `STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
# Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Markers created from Paths
# ==========================
#
# Any `~.path.Path` can be used as a marker. The following example shows two
# simple paths *star* and *circle*, and a more elaborate path of a circle with
# a cut-out star.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Advanced marker modifications with transform
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
# %%
# Setting marker cap style and join style
# =======================================
#
# Markers have default cap and join styles, but these can be
# customized when creating a MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
# %%
# Modifying the join style:
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
# %%
# .. tags::
#
# component: marker
# purpose: reference
| stable__gallery__lines_bars_and_markers__marker_reference | 0 | figure_000.png | Marker reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#unfilled-markers | https://matplotlib.org/stable/_downloads/af914017c64db37d6e814a5e9cdfb4a2/marker_reference.py | marker_reference.py | lines_bars_and_markers | ok | 8 | null | |
"""
================
Marker reference
================
Matplotlib supports multiple categories of markers which are selected using
the ``marker`` parameter of plot commands:
- `Unfilled markers`_
- `Filled markers`_
- `Markers created from TeX symbols`_
- `Markers created from Paths`_
For a list of all markers see also the `matplotlib.markers` documentation.
For example usages see
:doc:`/gallery/lines_bars_and_markers/scatter_star_poly`.
.. redirect-from:: /gallery/shapes_and_collections/marker_path
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
# %%
# Unfilled markers
# ================
# Unfilled markers are single-colored.
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Filled markers
# ==============
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# .. _marker_fill_styles:
#
# Marker fill styles
# ------------------
# The edge color and fill color of filled markers can be specified separately.
# Additionally, the ``fillstyle`` can be configured to be unfilled, fully
# filled, or half-filled in various directions. The half-filled styles use
# ``markerfacecoloralt`` as secondary fill color.
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
# %%
# Markers created from TeX symbols
# ================================
#
# Use :ref:`MathText <mathtext>`, to use custom marker symbols,
# like e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer
# to the `STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
# Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Markers created from Paths
# ==========================
#
# Any `~.path.Path` can be used as a marker. The following example shows two
# simple paths *star* and *circle*, and a more elaborate path of a circle with
# a cut-out star.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Advanced marker modifications with transform
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
# %%
# Setting marker cap style and join style
# =======================================
#
# Markers have default cap and join styles, but these can be
# customized when creating a MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
# %%
# Modifying the join style:
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
# %%
# .. tags::
#
# component: marker
# purpose: reference
| stable__gallery__lines_bars_and_markers__marker_reference | 1 | figure_001.png | Marker reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#unfilled-markers | https://matplotlib.org/stable/_downloads/af914017c64db37d6e814a5e9cdfb4a2/marker_reference.py | marker_reference.py | lines_bars_and_markers | ok | 8 | null | |
"""
================
Marker reference
================
Matplotlib supports multiple categories of markers which are selected using
the ``marker`` parameter of plot commands:
- `Unfilled markers`_
- `Filled markers`_
- `Markers created from TeX symbols`_
- `Markers created from Paths`_
For a list of all markers see also the `matplotlib.markers` documentation.
For example usages see
:doc:`/gallery/lines_bars_and_markers/scatter_star_poly`.
.. redirect-from:: /gallery/shapes_and_collections/marker_path
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
# %%
# Unfilled markers
# ================
# Unfilled markers are single-colored.
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Filled markers
# ==============
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# .. _marker_fill_styles:
#
# Marker fill styles
# ------------------
# The edge color and fill color of filled markers can be specified separately.
# Additionally, the ``fillstyle`` can be configured to be unfilled, fully
# filled, or half-filled in various directions. The half-filled styles use
# ``markerfacecoloralt`` as secondary fill color.
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
# %%
# Markers created from TeX symbols
# ================================
#
# Use :ref:`MathText <mathtext>`, to use custom marker symbols,
# like e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer
# to the `STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
# Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Markers created from Paths
# ==========================
#
# Any `~.path.Path` can be used as a marker. The following example shows two
# simple paths *star* and *circle*, and a more elaborate path of a circle with
# a cut-out star.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Advanced marker modifications with transform
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
# %%
# Setting marker cap style and join style
# =======================================
#
# Markers have default cap and join styles, but these can be
# customized when creating a MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
# %%
# Modifying the join style:
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
# %%
# .. tags::
#
# component: marker
# purpose: reference
| stable__gallery__lines_bars_and_markers__marker_reference | 2 | figure_002.png | Marker reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#unfilled-markers | https://matplotlib.org/stable/_downloads/af914017c64db37d6e814a5e9cdfb4a2/marker_reference.py | marker_reference.py | lines_bars_and_markers | ok | 8 | null | |
"""
================
Marker reference
================
Matplotlib supports multiple categories of markers which are selected using
the ``marker`` parameter of plot commands:
- `Unfilled markers`_
- `Filled markers`_
- `Markers created from TeX symbols`_
- `Markers created from Paths`_
For a list of all markers see also the `matplotlib.markers` documentation.
For example usages see
:doc:`/gallery/lines_bars_and_markers/scatter_star_poly`.
.. redirect-from:: /gallery/shapes_and_collections/marker_path
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
# %%
# Unfilled markers
# ================
# Unfilled markers are single-colored.
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Filled markers
# ==============
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# .. _marker_fill_styles:
#
# Marker fill styles
# ------------------
# The edge color and fill color of filled markers can be specified separately.
# Additionally, the ``fillstyle`` can be configured to be unfilled, fully
# filled, or half-filled in various directions. The half-filled styles use
# ``markerfacecoloralt`` as secondary fill color.
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
# %%
# Markers created from TeX symbols
# ================================
#
# Use :ref:`MathText <mathtext>`, to use custom marker symbols,
# like e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer
# to the `STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
# Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Markers created from Paths
# ==========================
#
# Any `~.path.Path` can be used as a marker. The following example shows two
# simple paths *star* and *circle*, and a more elaborate path of a circle with
# a cut-out star.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Advanced marker modifications with transform
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
# %%
# Setting marker cap style and join style
# =======================================
#
# Markers have default cap and join styles, but these can be
# customized when creating a MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
# %%
# Modifying the join style:
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
# %%
# .. tags::
#
# component: marker
# purpose: reference
| stable__gallery__lines_bars_and_markers__marker_reference | 3 | figure_003.png | Marker reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#unfilled-markers | https://matplotlib.org/stable/_downloads/af914017c64db37d6e814a5e9cdfb4a2/marker_reference.py | marker_reference.py | lines_bars_and_markers | ok | 8 | null | |
"""
================
Marker reference
================
Matplotlib supports multiple categories of markers which are selected using
the ``marker`` parameter of plot commands:
- `Unfilled markers`_
- `Filled markers`_
- `Markers created from TeX symbols`_
- `Markers created from Paths`_
For a list of all markers see also the `matplotlib.markers` documentation.
For example usages see
:doc:`/gallery/lines_bars_and_markers/scatter_star_poly`.
.. redirect-from:: /gallery/shapes_and_collections/marker_path
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
# %%
# Unfilled markers
# ================
# Unfilled markers are single-colored.
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Filled markers
# ==============
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# .. _marker_fill_styles:
#
# Marker fill styles
# ------------------
# The edge color and fill color of filled markers can be specified separately.
# Additionally, the ``fillstyle`` can be configured to be unfilled, fully
# filled, or half-filled in various directions. The half-filled styles use
# ``markerfacecoloralt`` as secondary fill color.
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
# %%
# Markers created from TeX symbols
# ================================
#
# Use :ref:`MathText <mathtext>`, to use custom marker symbols,
# like e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer
# to the `STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
# Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Markers created from Paths
# ==========================
#
# Any `~.path.Path` can be used as a marker. The following example shows two
# simple paths *star* and *circle*, and a more elaborate path of a circle with
# a cut-out star.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Advanced marker modifications with transform
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
# %%
# Setting marker cap style and join style
# =======================================
#
# Markers have default cap and join styles, but these can be
# customized when creating a MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
# %%
# Modifying the join style:
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
# %%
# .. tags::
#
# component: marker
# purpose: reference
| stable__gallery__lines_bars_and_markers__marker_reference | 4 | figure_004.png | Marker reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#unfilled-markers | https://matplotlib.org/stable/_downloads/af914017c64db37d6e814a5e9cdfb4a2/marker_reference.py | marker_reference.py | lines_bars_and_markers | ok | 8 | null | |
"""
================
Marker reference
================
Matplotlib supports multiple categories of markers which are selected using
the ``marker`` parameter of plot commands:
- `Unfilled markers`_
- `Filled markers`_
- `Markers created from TeX symbols`_
- `Markers created from Paths`_
For a list of all markers see also the `matplotlib.markers` documentation.
For example usages see
:doc:`/gallery/lines_bars_and_markers/scatter_star_poly`.
.. redirect-from:: /gallery/shapes_and_collections/marker_path
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
# %%
# Unfilled markers
# ================
# Unfilled markers are single-colored.
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Filled markers
# ==============
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# .. _marker_fill_styles:
#
# Marker fill styles
# ------------------
# The edge color and fill color of filled markers can be specified separately.
# Additionally, the ``fillstyle`` can be configured to be unfilled, fully
# filled, or half-filled in various directions. The half-filled styles use
# ``markerfacecoloralt`` as secondary fill color.
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
# %%
# Markers created from TeX symbols
# ================================
#
# Use :ref:`MathText <mathtext>`, to use custom marker symbols,
# like e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer
# to the `STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
# Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Markers created from Paths
# ==========================
#
# Any `~.path.Path` can be used as a marker. The following example shows two
# simple paths *star* and *circle*, and a more elaborate path of a circle with
# a cut-out star.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Advanced marker modifications with transform
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
# %%
# Setting marker cap style and join style
# =======================================
#
# Markers have default cap and join styles, but these can be
# customized when creating a MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
# %%
# Modifying the join style:
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
# %%
# .. tags::
#
# component: marker
# purpose: reference
| stable__gallery__lines_bars_and_markers__marker_reference | 5 | figure_005.png | Marker reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#unfilled-markers | https://matplotlib.org/stable/_downloads/af914017c64db37d6e814a5e9cdfb4a2/marker_reference.py | marker_reference.py | lines_bars_and_markers | ok | 8 | null | |
"""
================
Marker reference
================
Matplotlib supports multiple categories of markers which are selected using
the ``marker`` parameter of plot commands:
- `Unfilled markers`_
- `Filled markers`_
- `Markers created from TeX symbols`_
- `Markers created from Paths`_
For a list of all markers see also the `matplotlib.markers` documentation.
For example usages see
:doc:`/gallery/lines_bars_and_markers/scatter_star_poly`.
.. redirect-from:: /gallery/shapes_and_collections/marker_path
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
# %%
# Unfilled markers
# ================
# Unfilled markers are single-colored.
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Filled markers
# ==============
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# .. _marker_fill_styles:
#
# Marker fill styles
# ------------------
# The edge color and fill color of filled markers can be specified separately.
# Additionally, the ``fillstyle`` can be configured to be unfilled, fully
# filled, or half-filled in various directions. The half-filled styles use
# ``markerfacecoloralt`` as secondary fill color.
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
# %%
# Markers created from TeX symbols
# ================================
#
# Use :ref:`MathText <mathtext>`, to use custom marker symbols,
# like e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer
# to the `STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
# Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Markers created from Paths
# ==========================
#
# Any `~.path.Path` can be used as a marker. The following example shows two
# simple paths *star* and *circle*, and a more elaborate path of a circle with
# a cut-out star.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Advanced marker modifications with transform
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
# %%
# Setting marker cap style and join style
# =======================================
#
# Markers have default cap and join styles, but these can be
# customized when creating a MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
# %%
# Modifying the join style:
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
# %%
# .. tags::
#
# component: marker
# purpose: reference
| stable__gallery__lines_bars_and_markers__marker_reference | 6 | figure_006.png | Marker reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#unfilled-markers | https://matplotlib.org/stable/_downloads/af914017c64db37d6e814a5e9cdfb4a2/marker_reference.py | marker_reference.py | lines_bars_and_markers | ok | 8 | null | |
"""
================
Marker reference
================
Matplotlib supports multiple categories of markers which are selected using
the ``marker`` parameter of plot commands:
- `Unfilled markers`_
- `Filled markers`_
- `Markers created from TeX symbols`_
- `Markers created from Paths`_
For a list of all markers see also the `matplotlib.markers` documentation.
For example usages see
:doc:`/gallery/lines_bars_and_markers/scatter_star_poly`.
.. redirect-from:: /gallery/shapes_and_collections/marker_path
"""
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
# %%
# Unfilled markers
# ================
# Unfilled markers are single-colored.
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Filled markers
# ==============
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# .. _marker_fill_styles:
#
# Marker fill styles
# ------------------
# The edge color and fill color of filled markers can be specified separately.
# Additionally, the ``fillstyle`` can be configured to be unfilled, fully
# filled, or half-filled in various directions. The half-filled styles use
# ``markerfacecoloralt`` as secondary fill color.
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
# %%
# Markers created from TeX symbols
# ================================
#
# Use :ref:`MathText <mathtext>`, to use custom marker symbols,
# like e.g. ``"$\u266B$"``. For an overview over the STIX font symbols refer
# to the `STIX font table <http://www.stixfonts.org/allGlyphs.html>`_.
# Also see the :doc:`/gallery/text_labels_and_annotations/stix_fonts_demo`.
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$", r"$\mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"\$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Markers created from Paths
# ==========================
#
# Any `~.path.Path` can be used as a marker. The following example shows two
# simple paths *star* and *circle*, and a more elaborate path of a circle with
# a cut-out star.
import numpy as np
import matplotlib.path as mpath
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
# %%
# Advanced marker modifications with transform
# ============================================
#
# Markers can be modified by passing a transform to the MarkerStyle
# constructor. Following example shows how a supplied rotation is applied to
# several marker shapes.
common_style = {k: v for k, v in filled_marker_style.items() if k != 'marker'}
angles = [0, 10, 20, 30, 45, 60, 90]
fig, ax = plt.subplots()
fig.suptitle('Rotated markers', fontsize=14)
ax.text(-0.5, 0, 'Filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 0, marker=MarkerStyle('o', 'left', t), **common_style)
ax.text(-0.5, 1, 'Un-filled marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
ax.plot(x, 1, marker=MarkerStyle('1', 'left', t), **common_style)
ax.text(-0.5, 2, 'Equation marker', **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
eq = r'$\frac{1}{x}$'
ax.plot(x, 2, marker=MarkerStyle(eq, 'left', t), **common_style)
for x, theta in enumerate(angles):
ax.text(x, 2.5, f"{theta}°", horizontalalignment="center")
format_axes(ax)
fig.tight_layout()
# %%
# Setting marker cap style and join style
# =======================================
#
# Markers have default cap and join styles, but these can be
# customized when creating a MarkerStyle.
from matplotlib.markers import CapStyle, JoinStyle
marker_inner = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown',
markeredgewidth=8,
)
marker_outer = dict(markersize=35,
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='white',
markeredgewidth=1,
)
fig, ax = plt.subplots()
fig.suptitle('Marker CapStyle', fontsize=14)
fig.subplots_adjust(left=0.1)
for y, cap_style in enumerate(CapStyle):
ax.text(-0.5, y, cap_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('1', transform=t, capstyle=cap_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.plot(x, y, marker=m, **marker_outer)
ax.text(x, len(CapStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
# %%
# Modifying the join style:
fig, ax = plt.subplots()
fig.suptitle('Marker JoinStyle', fontsize=14)
fig.subplots_adjust(left=0.05)
for y, join_style in enumerate(JoinStyle):
ax.text(-0.5, y, join_style.name, **text_style)
for x, theta in enumerate(angles):
t = Affine2D().rotate_deg(theta)
m = MarkerStyle('*', transform=t, joinstyle=join_style)
ax.plot(x, y, marker=m, **marker_inner)
ax.text(x, len(JoinStyle) - .5, f'{theta}°', ha='center')
format_axes(ax)
plt.show()
# %%
# .. tags::
#
# component: marker
# purpose: reference
| stable__gallery__lines_bars_and_markers__marker_reference | 7 | figure_007.png | Marker reference — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#unfilled-markers | https://matplotlib.org/stable/_downloads/af914017c64db37d6e814a5e9cdfb4a2/marker_reference.py | marker_reference.py | lines_bars_and_markers | ok | 8 | null | |
"""
==============
Markevery Demo
==============
The ``markevery`` property of `.Line2D` allows drawing markers at a subset of
data points.
The list of possible parameters is specified at `.Line2D.set_markevery`.
In short:
- A single integer N draws every N-th marker.
- A tuple of integers (start, N) draws every N-th marker, starting at data
index *start*.
- A list of integers draws the markers at the specified indices.
- A slice draws the markers at the sliced indices.
- A float specifies the distance between markers as a fraction of the Axes
diagonal in screen space. This will lead to a visually uniform distribution
of the points along the line, irrespective of scales and zooming.
"""
import matplotlib.pyplot as plt
import numpy as np
# define a list of markevery cases to plot
cases = [
None,
8,
(30, 8),
[16, 24, 32],
[0, -1],
slice(100, 200, 3),
0.1,
0.4,
(0.2, 0.4)
]
# data points
delta = 0.11
x = np.linspace(0, 10 - 2 * delta, 200) + delta
y = np.sin(x) + 1.0 + delta
# %%
# markevery with linear scales
# ----------------------------
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
# %%
# markevery with log scales
# -------------------------
#
# Note that the log scale causes a visual asymmetry in the marker distance for
# when subsampling the data using an integer. In contrast, subsampling on
# fraction of figure size creates even distributions, because it's based on
# fractions of the Axes diagonal, not on data coordinates or data indices.
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.set_xscale('log')
ax.set_yscale('log')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
# %%
# markevery on zoomed plots
# -------------------------
#
# Integer-based *markevery* specifications select points from the underlying
# data and are independent on the view. In contrast, float-based specifications
# are related to the Axes diagonal. While zooming does not change the Axes
# diagonal, it changes the displayed data range, and more points will be
# displayed when zooming.
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
ax.set_xlim((6, 6.7))
ax.set_ylim((1.1, 1.7))
# %%
# markevery on polar plots
# ------------------------
r = np.linspace(0, 3.0, 200)
theta = 2 * np.pi * r
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained',
subplot_kw={'projection': 'polar'})
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(theta, r, 'o', ls='-', ms=4, markevery=markevery)
plt.show()
# %%
# .. tags::
#
# component: marker
# plot-type: line
# level: beginner
| stable__gallery__lines_bars_and_markers__markevery_demo | 0 | figure_000.png | Markevery Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/markevery_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-markevery-demo-py | https://matplotlib.org/stable/_downloads/d4832f59edf5628fed3ec2eee2cecbf9/markevery_demo.py | markevery_demo.py | lines_bars_and_markers | ok | 4 | null | |
"""
==============
Markevery Demo
==============
The ``markevery`` property of `.Line2D` allows drawing markers at a subset of
data points.
The list of possible parameters is specified at `.Line2D.set_markevery`.
In short:
- A single integer N draws every N-th marker.
- A tuple of integers (start, N) draws every N-th marker, starting at data
index *start*.
- A list of integers draws the markers at the specified indices.
- A slice draws the markers at the sliced indices.
- A float specifies the distance between markers as a fraction of the Axes
diagonal in screen space. This will lead to a visually uniform distribution
of the points along the line, irrespective of scales and zooming.
"""
import matplotlib.pyplot as plt
import numpy as np
# define a list of markevery cases to plot
cases = [
None,
8,
(30, 8),
[16, 24, 32],
[0, -1],
slice(100, 200, 3),
0.1,
0.4,
(0.2, 0.4)
]
# data points
delta = 0.11
x = np.linspace(0, 10 - 2 * delta, 200) + delta
y = np.sin(x) + 1.0 + delta
# %%
# markevery with linear scales
# ----------------------------
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
# %%
# markevery with log scales
# -------------------------
#
# Note that the log scale causes a visual asymmetry in the marker distance for
# when subsampling the data using an integer. In contrast, subsampling on
# fraction of figure size creates even distributions, because it's based on
# fractions of the Axes diagonal, not on data coordinates or data indices.
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.set_xscale('log')
ax.set_yscale('log')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
# %%
# markevery on zoomed plots
# -------------------------
#
# Integer-based *markevery* specifications select points from the underlying
# data and are independent on the view. In contrast, float-based specifications
# are related to the Axes diagonal. While zooming does not change the Axes
# diagonal, it changes the displayed data range, and more points will be
# displayed when zooming.
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
ax.set_xlim((6, 6.7))
ax.set_ylim((1.1, 1.7))
# %%
# markevery on polar plots
# ------------------------
r = np.linspace(0, 3.0, 200)
theta = 2 * np.pi * r
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained',
subplot_kw={'projection': 'polar'})
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(theta, r, 'o', ls='-', ms=4, markevery=markevery)
plt.show()
# %%
# .. tags::
#
# component: marker
# plot-type: line
# level: beginner
| stable__gallery__lines_bars_and_markers__markevery_demo | 1 | figure_001.png | Markevery Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/markevery_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-markevery-demo-py | https://matplotlib.org/stable/_downloads/d4832f59edf5628fed3ec2eee2cecbf9/markevery_demo.py | markevery_demo.py | lines_bars_and_markers | ok | 4 | null | |
"""
==============
Markevery Demo
==============
The ``markevery`` property of `.Line2D` allows drawing markers at a subset of
data points.
The list of possible parameters is specified at `.Line2D.set_markevery`.
In short:
- A single integer N draws every N-th marker.
- A tuple of integers (start, N) draws every N-th marker, starting at data
index *start*.
- A list of integers draws the markers at the specified indices.
- A slice draws the markers at the sliced indices.
- A float specifies the distance between markers as a fraction of the Axes
diagonal in screen space. This will lead to a visually uniform distribution
of the points along the line, irrespective of scales and zooming.
"""
import matplotlib.pyplot as plt
import numpy as np
# define a list of markevery cases to plot
cases = [
None,
8,
(30, 8),
[16, 24, 32],
[0, -1],
slice(100, 200, 3),
0.1,
0.4,
(0.2, 0.4)
]
# data points
delta = 0.11
x = np.linspace(0, 10 - 2 * delta, 200) + delta
y = np.sin(x) + 1.0 + delta
# %%
# markevery with linear scales
# ----------------------------
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
# %%
# markevery with log scales
# -------------------------
#
# Note that the log scale causes a visual asymmetry in the marker distance for
# when subsampling the data using an integer. In contrast, subsampling on
# fraction of figure size creates even distributions, because it's based on
# fractions of the Axes diagonal, not on data coordinates or data indices.
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.set_xscale('log')
ax.set_yscale('log')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
# %%
# markevery on zoomed plots
# -------------------------
#
# Integer-based *markevery* specifications select points from the underlying
# data and are independent on the view. In contrast, float-based specifications
# are related to the Axes diagonal. While zooming does not change the Axes
# diagonal, it changes the displayed data range, and more points will be
# displayed when zooming.
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
ax.set_xlim((6, 6.7))
ax.set_ylim((1.1, 1.7))
# %%
# markevery on polar plots
# ------------------------
r = np.linspace(0, 3.0, 200)
theta = 2 * np.pi * r
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained',
subplot_kw={'projection': 'polar'})
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(theta, r, 'o', ls='-', ms=4, markevery=markevery)
plt.show()
# %%
# .. tags::
#
# component: marker
# plot-type: line
# level: beginner
| stable__gallery__lines_bars_and_markers__markevery_demo | 2 | figure_002.png | Markevery Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/markevery_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-markevery-demo-py | https://matplotlib.org/stable/_downloads/d4832f59edf5628fed3ec2eee2cecbf9/markevery_demo.py | markevery_demo.py | lines_bars_and_markers | ok | 4 | null | |
"""
==============
Markevery Demo
==============
The ``markevery`` property of `.Line2D` allows drawing markers at a subset of
data points.
The list of possible parameters is specified at `.Line2D.set_markevery`.
In short:
- A single integer N draws every N-th marker.
- A tuple of integers (start, N) draws every N-th marker, starting at data
index *start*.
- A list of integers draws the markers at the specified indices.
- A slice draws the markers at the sliced indices.
- A float specifies the distance between markers as a fraction of the Axes
diagonal in screen space. This will lead to a visually uniform distribution
of the points along the line, irrespective of scales and zooming.
"""
import matplotlib.pyplot as plt
import numpy as np
# define a list of markevery cases to plot
cases = [
None,
8,
(30, 8),
[16, 24, 32],
[0, -1],
slice(100, 200, 3),
0.1,
0.4,
(0.2, 0.4)
]
# data points
delta = 0.11
x = np.linspace(0, 10 - 2 * delta, 200) + delta
y = np.sin(x) + 1.0 + delta
# %%
# markevery with linear scales
# ----------------------------
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
# %%
# markevery with log scales
# -------------------------
#
# Note that the log scale causes a visual asymmetry in the marker distance for
# when subsampling the data using an integer. In contrast, subsampling on
# fraction of figure size creates even distributions, because it's based on
# fractions of the Axes diagonal, not on data coordinates or data indices.
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.set_xscale('log')
ax.set_yscale('log')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
# %%
# markevery on zoomed plots
# -------------------------
#
# Integer-based *markevery* specifications select points from the underlying
# data and are independent on the view. In contrast, float-based specifications
# are related to the Axes diagonal. While zooming does not change the Axes
# diagonal, it changes the displayed data range, and more points will be
# displayed when zooming.
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained')
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=markevery)
ax.set_xlim((6, 6.7))
ax.set_ylim((1.1, 1.7))
# %%
# markevery on polar plots
# ------------------------
r = np.linspace(0, 3.0, 200)
theta = 2 * np.pi * r
fig, axs = plt.subplots(3, 3, figsize=(10, 6), layout='constrained',
subplot_kw={'projection': 'polar'})
for ax, markevery in zip(axs.flat, cases):
ax.set_title(f'markevery={markevery}')
ax.plot(theta, r, 'o', ls='-', ms=4, markevery=markevery)
plt.show()
# %%
# .. tags::
#
# component: marker
# plot-type: line
# level: beginner
| stable__gallery__lines_bars_and_markers__markevery_demo | 3 | figure_003.png | Markevery Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/markevery_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-markevery-demo-py | https://matplotlib.org/stable/_downloads/d4832f59edf5628fed3ec2eee2cecbf9/markevery_demo.py | markevery_demo.py | lines_bars_and_markers | ok | 4 | null | |
"""
==============================
Plotting masked and NaN values
==============================
Sometimes you need to plot data with missing values.
One possibility is to simply remove undesired data points. The line plotted
through the remaining data will be continuous, and not indicate where the
missing data is located.
If it is useful to have gaps in the line where the data is missing, then the
undesired points can be indicated using a `masked array`_ or by setting their
values to NaN. No marker will be drawn where either x or y are masked and, if
plotting with a line, it will be broken there.
.. _masked array:
https://numpy.org/doc/stable/reference/maskedarray.generic.html
The following example illustrates the three cases:
1) Removing points.
2) Masking points.
3) Setting to NaN.
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi/2, np.pi/2, 31)
y = np.cos(x)**3
# 1) remove points where y > 0.7
x2 = x[y <= 0.7]
y2 = y[y <= 0.7]
# 2) mask points where y > 0.7
y3 = np.ma.masked_where(y > 0.7, y)
# 3) set to NaN where y > 0.7
y4 = y.copy()
y4[y3 > 0.7] = np.nan
plt.plot(x*0.1, y, 'o-', color='lightgrey', label='No mask')
plt.plot(x2*0.4, y2, 'o-', label='Points removed')
plt.plot(x*0.7, y3, 'o-', label='Masked values')
plt.plot(x*1.0, y4, 'o-', label='NaN values')
plt.legend()
plt.title('Masked and NaN data')
plt.show()
# %%
# .. tags::
#
# plot-type: line
# level: intermediate
| stable__gallery__lines_bars_and_markers__masked_demo | 0 | figure_000.png | Plotting masked and NaN values — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/masked_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-masked-demo-py | https://matplotlib.org/stable/_downloads/285cf9001b13973e75842eb0b810371f/masked_demo.py | masked_demo.py | lines_bars_and_markers | ok | 1 | null | |
"""
==================
Multicolored lines
==================
The example shows two ways to plot a line with the a varying color defined by
a third value. The first example defines the color at each (x, y) point.
The second example defines the color between pairs of points, so the length
of the color value list is one less than the length of the x and y lists.
Color values at points
----------------------
"""
import warnings
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
def colored_line(x, y, c, ax, **lc_kwargs):
"""
Plot a line with a color specified along the line by a third value.
It does this by creating a collection of line segments. Each line segment is
made up of two straight lines each connecting the current (x, y) point to the
midpoints of the lines connecting the current point with its two neighbors.
This creates a smooth line with no gaps between the line segments.
Parameters
----------
x, y : array-like
The horizontal and vertical coordinates of the data points.
c : array-like
The color values, which should be the same size as x and y.
ax : Axes
Axis object on which to plot the colored line.
**lc_kwargs
Any additional arguments to pass to matplotlib.collections.LineCollection
constructor. This should not include the array keyword argument because
that is set to the color argument. If provided, it will be overridden.
Returns
-------
matplotlib.collections.LineCollection
The generated line collection representing the colored line.
"""
if "array" in lc_kwargs:
warnings.warn('The provided "array" keyword argument will be overridden')
# Default the capstyle to butt so that the line segments smoothly line up
default_kwargs = {"capstyle": "butt"}
default_kwargs.update(lc_kwargs)
# Compute the midpoints of the line segments. Include the first and last points
# twice so we don't need any special syntax later to handle them.
x = np.asarray(x)
y = np.asarray(y)
x_midpts = np.hstack((x[0], 0.5 * (x[1:] + x[:-1]), x[-1]))
y_midpts = np.hstack((y[0], 0.5 * (y[1:] + y[:-1]), y[-1]))
# Determine the start, middle, and end coordinate pair of each line segment.
# Use the reshape to add an extra dimension so each pair of points is in its
# own list. Then concatenate them to create:
# [
# [(x1_start, y1_start), (x1_mid, y1_mid), (x1_end, y1_end)],
# [(x2_start, y2_start), (x2_mid, y2_mid), (x2_end, y2_end)],
# ...
# ]
coord_start = np.column_stack((x_midpts[:-1], y_midpts[:-1]))[:, np.newaxis, :]
coord_mid = np.column_stack((x, y))[:, np.newaxis, :]
coord_end = np.column_stack((x_midpts[1:], y_midpts[1:]))[:, np.newaxis, :]
segments = np.concatenate((coord_start, coord_mid, coord_end), axis=1)
lc = LineCollection(segments, **default_kwargs)
lc.set_array(c) # set the colors of each segment
return ax.add_collection(lc)
# -------------- Create and show plot --------------
# Some arbitrary function that gives x, y, and color values
t = np.linspace(-7.4, -0.5, 200)
x = 0.9 * np.sin(t)
y = 0.9 * np.cos(1.6 * t)
color = np.linspace(0, 2, t.size)
# Create a figure and plot the line on it
fig1, ax1 = plt.subplots()
lines = colored_line(x, y, color, ax1, linewidth=10, cmap="plasma")
fig1.colorbar(lines) # add a color legend
# Set the axis limits and tick positions
ax1.set_xlim(-1, 1)
ax1.set_ylim(-1, 1)
ax1.set_xticks((-1, 0, 1))
ax1.set_yticks((-1, 0, 1))
ax1.set_title("Color at each point")
plt.show()
####################################################################
# This method is designed to give a smooth impression when distances and color
# differences between adjacent points are not too large. The following example
# does not meet this criteria and by that serves to illustrate the segmentation
# and coloring mechanism.
x = [0, 1, 2, 3, 4]
y = [0, 1, 2, 1, 1]
c = [1, 2, 3, 4, 5]
fig, ax = plt.subplots()
ax.scatter(x, y, c=c, cmap='rainbow')
colored_line(x, y, c=c, ax=ax, cmap='rainbow')
plt.show()
####################################################################
# Color values between points
# ---------------------------
#
def colored_line_between_pts(x, y, c, ax, **lc_kwargs):
"""
Plot a line with a color specified between (x, y) points by a third value.
It does this by creating a collection of line segments between each pair of
neighboring points. The color of each segment is determined by the
made up of two straight lines each connecting the current (x, y) point to the
midpoints of the lines connecting the current point with its two neighbors.
This creates a smooth line with no gaps between the line segments.
Parameters
----------
x, y : array-like
The horizontal and vertical coordinates of the data points.
c : array-like
The color values, which should have a size one less than that of x and y.
ax : Axes
Axis object on which to plot the colored line.
**lc_kwargs
Any additional arguments to pass to matplotlib.collections.LineCollection
constructor. This should not include the array keyword argument because
that is set to the color argument. If provided, it will be overridden.
Returns
-------
matplotlib.collections.LineCollection
The generated line collection representing the colored line.
"""
if "array" in lc_kwargs:
warnings.warn('The provided "array" keyword argument will be overridden')
# Check color array size (LineCollection still works, but values are unused)
if len(c) != len(x) - 1:
warnings.warn(
"The c argument should have a length one less than the length of x and y. "
"If it has the same length, use the colored_line function instead."
)
# Create a set of line segments so that we can color them individually
# This creates the points as an N x 1 x 2 array so that we can stack points
# together easily to get the segments. The segments array for line collection
# needs to be (numlines) x (points per line) x 2 (for x and y)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, **lc_kwargs)
# Set the values used for colormapping
lc.set_array(c)
return ax.add_collection(lc)
# -------------- Create and show plot --------------
x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
dydx = np.cos(0.5 * (x[:-1] + x[1:])) # first derivative
fig2, ax2 = plt.subplots()
line = colored_line_between_pts(x, y, dydx, ax2, linewidth=2, cmap="viridis")
fig2.colorbar(line, ax=ax2, label="dy/dx")
ax2.set_xlim(x.min(), x.max())
ax2.set_ylim(-1.1, 1.1)
ax2.set_title("Color between points")
plt.show()
# %%
# .. tags::
#
# styling: color
# styling: linestyle
# plot-type: line
# level: intermediate
| stable__gallery__lines_bars_and_markers__multicolored_line | 0 | figure_000.png | Multicolored lines — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/multicolored_line.html#sphx-glr-download-gallery-lines-bars-and-markers-multicolored-line-py | https://matplotlib.org/stable/_downloads/dde8bce4a3266a4b3702098ddc49f236/multicolored_line.py | multicolored_line.py | lines_bars_and_markers | ok | 3 | null | |
"""
==============================================
Mapping marker properties to multivariate data
==============================================
This example shows how to use different properties of markers to plot
multivariate datasets. Here we represent a successful baseball throw as a
smiley face with marker size mapped to the skill of thrower, marker rotation to
the take-off angle, and thrust to the marker color.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import Normalize
from matplotlib.markers import MarkerStyle
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D
SUCCESS_SYMBOLS = [
TextPath((0, 0), "☹"),
TextPath((0, 0), "😒"),
TextPath((0, 0), "☺"),
]
N = 25
np.random.seed(42)
skills = np.random.uniform(5, 80, size=N) * 0.1 + 5
takeoff_angles = np.random.normal(0, 90, N)
thrusts = np.random.uniform(size=N)
successful = np.random.randint(0, 3, size=N)
positions = np.random.normal(size=(N, 2)) * 5
data = zip(skills, takeoff_angles, thrusts, successful, positions)
cmap = plt.colormaps["plasma"]
fig, ax = plt.subplots()
fig.suptitle("Throwing success", size=14)
for skill, takeoff, thrust, mood, pos in data:
t = Affine2D().scale(skill).rotate_deg(takeoff)
m = MarkerStyle(SUCCESS_SYMBOLS[mood], transform=t)
ax.plot(pos[0], pos[1], marker=m, color=cmap(thrust))
fig.colorbar(plt.cm.ScalarMappable(norm=Normalize(0, 1), cmap=cmap),
ax=ax, label="Normalized Thrust [a.u.]")
ax.set_xlabel("X position [m]")
ax.set_ylabel("Y position [m]")
plt.show()
# %%
# .. tags::
#
# component: marker
# styling: color,
# styling: shape
# level: beginner
# purpose: fun
| stable__gallery__lines_bars_and_markers__multivariate_marker_plot | 0 | figure_000.png | Mapping marker properties to multivariate data — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/multivariate_marker_plot.html#sphx-glr-download-gallery-lines-bars-and-markers-multivariate-marker-plot-py | https://matplotlib.org/stable/_downloads/0c9f82be1ea4cded0763a4430f4a0e83/multivariate_marker_plot.py | multivariate_marker_plot.py | lines_bars_and_markers | ok | 1 | null | |
"""
============================
Power spectral density (PSD)
============================
Plotting power spectral density (PSD) using `~.Axes.psd`.
The PSD is a common plot in the field of signal processing. NumPy has
many useful libraries for computing a PSD. Below we demo a few examples
of how this can be accomplished and visualized with Matplotlib.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
# Fixing random state for reproducibility
np.random.seed(19680801)
dt = 0.01
t = np.arange(0, 10, dt)
nse = np.random.randn(len(t))
r = np.exp(-t / 0.05)
cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
s = 0.1 * np.sin(2 * np.pi * t) + cnse
fig, (ax0, ax1) = plt.subplots(2, 1, layout='constrained')
ax0.plot(t, s)
ax0.set_xlabel('Time (s)')
ax0.set_ylabel('Signal')
ax1.psd(s, NFFT=512, Fs=1 / dt)
plt.show()
# %%
# Compare this with the equivalent Matlab code to accomplish the same thing::
#
# dt = 0.01;
# t = [0:dt:10];
# nse = randn(size(t));
# r = exp(-t/0.05);
# cnse = conv(nse, r)*dt;
# cnse = cnse(1:length(t));
# s = 0.1*sin(2*pi*t) + cnse;
#
# subplot(211)
# plot(t, s)
# subplot(212)
# psd(s, 512, 1/dt)
#
# Below we'll show a slightly more complex example that demonstrates
# how padding affects the resulting PSD.
dt = np.pi / 100.
fs = 1. / dt
t = np.arange(0, 8, dt)
y = 10. * np.sin(2 * np.pi * 4 * t) + 5. * np.sin(2 * np.pi * 4.25 * t)
y = y + np.random.randn(*t.shape)
# Plot the raw time series
fig, axs = plt.subplot_mosaic([
['signal', 'signal', 'signal'],
['zero padding', 'block size', 'overlap'],
], layout='constrained')
axs['signal'].plot(t, y)
axs['signal'].set_xlabel('Time (s)')
axs['signal'].set_ylabel('Signal')
# Plot the PSD with different amounts of zero padding. This uses the entire
# time series at once
axs['zero padding'].psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
axs['zero padding'].psd(y, NFFT=len(t), pad_to=len(t) * 2, Fs=fs)
axs['zero padding'].psd(y, NFFT=len(t), pad_to=len(t) * 4, Fs=fs)
# Plot the PSD with different block sizes, Zero pad to the length of the
# original data sequence.
axs['block size'].psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
axs['block size'].psd(y, NFFT=len(t) // 2, pad_to=len(t), Fs=fs)
axs['block size'].psd(y, NFFT=len(t) // 4, pad_to=len(t), Fs=fs)
axs['block size'].set_ylabel('')
# Plot the PSD with different amounts of overlap between blocks
axs['overlap'].psd(y, NFFT=len(t) // 2, pad_to=len(t), noverlap=0, Fs=fs)
axs['overlap'].psd(y, NFFT=len(t) // 2, pad_to=len(t),
noverlap=int(0.025 * len(t)), Fs=fs)
axs['overlap'].psd(y, NFFT=len(t) // 2, pad_to=len(t),
noverlap=int(0.1 * len(t)), Fs=fs)
axs['overlap'].set_ylabel('')
axs['overlap'].set_title('overlap')
for title, ax in axs.items():
if title == 'signal':
continue
ax.set_title(title)
ax.sharex(axs['zero padding'])
ax.sharey(axs['zero padding'])
plt.show()
# %%
# This is a ported version of a MATLAB example from the signal
# processing toolbox that showed some difference at one time between
# Matplotlib's and MATLAB's scaling of the PSD.
fs = 1000
t = np.linspace(0, 0.3, 301)
A = np.array([2, 8]).reshape(-1, 1)
f = np.array([150, 140]).reshape(-1, 1)
xn = (A * np.sin(2 * np.pi * f * t)).sum(axis=0)
xn += 5 * np.random.randn(*t.shape)
fig, (ax0, ax1) = plt.subplots(ncols=2, layout='constrained')
yticks = np.arange(-50, 30, 10)
yrange = (yticks[0], yticks[-1])
xticks = np.arange(0, 550, 100)
ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024,
scale_by_freq=True)
ax0.set_title('Periodogram')
ax0.set_yticks(yticks)
ax0.set_xticks(xticks)
ax0.grid(True)
ax0.set_ylim(yrange)
ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75,
scale_by_freq=True)
ax1.set_title('Welch')
ax1.set_xticks(xticks)
ax1.set_yticks(yticks)
ax1.set_ylabel('') # overwrite the y-label added by `psd`
ax1.grid(True)
ax1.set_ylim(yrange)
plt.show()
# %%
# This is a ported version of a MATLAB example from the signal
# processing toolbox that showed some difference at one time between
# Matplotlib's and MATLAB's scaling of the PSD.
#
# It uses a complex signal so we can see that complex PSD's work properly.
prng = np.random.RandomState(19680801) # to ensure reproducibility
fs = 1000
t = np.linspace(0, 0.3, 301)
A = np.array([2, 8]).reshape(-1, 1)
f = np.array([150, 140]).reshape(-1, 1)
xn = (A * np.exp(2j * np.pi * f * t)).sum(axis=0) + 5 * prng.randn(*t.shape)
fig, (ax0, ax1) = plt.subplots(ncols=2, layout='constrained')
yticks = np.arange(-50, 30, 10)
yrange = (yticks[0], yticks[-1])
xticks = np.arange(-500, 550, 200)
ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024,
scale_by_freq=True)
ax0.set_title('Periodogram')
ax0.set_yticks(yticks)
ax0.set_xticks(xticks)
ax0.grid(True)
ax0.set_ylim(yrange)
ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75,
scale_by_freq=True)
ax1.set_title('Welch')
ax1.set_xticks(xticks)
ax1.set_yticks(yticks)
ax1.set_ylabel('') # overwrite the y-label added by `psd`
ax1.grid(True)
ax1.set_ylim(yrange)
plt.show()
# %%
# .. tags::
#
# domain: signal-processing
# plot-type: line
# level: intermediate
| stable__gallery__lines_bars_and_markers__psd_demo | 0 | figure_000.png | Power spectral density (PSD) — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/psd_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-psd-demo-py | https://matplotlib.org/stable/_downloads/5297dff52c244336df5a0ee552a4abbf/psd_demo.py | psd_demo.py | lines_bars_and_markers | ok | 4 | null | |
"""
=============
Scatter Demo2
=============
Demo of scatter plot with varying marker colors and sizes.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
# Load a numpy record array from yahoo csv data with fields date, open, high,
# low, close, volume, adj_close from the mpl-data/sample_data directory. The
# record array stores the date as an np.datetime64 with a day unit ('D') in
# the date column.
price_data = cbook.get_sample_data('goog.npz')['price_data']
price_data = price_data[-250:] # get the most recent 250 trading days
delta1 = np.diff(price_data["adj_close"]) / price_data["adj_close"][:-1]
# Marker size in units of points^2
volume = (15 * price_data["volume"][:-2] / price_data["volume"][0])**2
close = 0.003 * price_data["close"][:-2] / 0.003 * price_data["open"][:-2]
fig, ax = plt.subplots()
ax.scatter(delta1[:-1], delta1[1:], c=close, s=volume, alpha=0.5)
ax.set_xlabel(r'$\Delta_i$', fontsize=15)
ax.set_ylabel(r'$\Delta_{i+1}$', fontsize=15)
ax.set_title('Volume and percent change')
ax.grid(True)
fig.tight_layout()
plt.show()
# %%
# .. tags::
#
# component: marker
# component: color
# plot-style: scatter
# level: beginner
| stable__gallery__lines_bars_and_markers__scatter_demo2 | 0 | figure_000.png | Scatter Demo2 — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/scatter_demo2.html#sphx-glr-download-gallery-lines-bars-and-markers-scatter-demo2-py | https://matplotlib.org/stable/_downloads/5b9eb7dec3f843b16e67ad82e4647a08/scatter_demo2.py | scatter_demo2.py | lines_bars_and_markers | ok | 1 | null | |
"""
============================
Scatter plot with histograms
============================
Add histograms to the x-axes and y-axes margins of a scatter plot.
This layout features a central scatter plot illustrating the relationship
between x and y, a histogram at the top displaying the distribution of x, and a
histogram on the right showing the distribution of y.
For a nice alignment of the main Axes with the marginals, two options are shown
below:
.. contents::
:local:
While `.Axes.inset_axes` may be a bit more complex, it allows correct handling
of main Axes with a fixed aspect ratio.
Let us first define a function that takes x and y data as input, as well as
three Axes, the main Axes for the scatter, and two marginal Axes. It will then
create the scatter and histograms inside the provided Axes.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
# some random data
x = np.random.randn(1000)
y = np.random.randn(1000)
def scatter_hist(x, y, ax, ax_histx, ax_histy):
# no labels
ax_histx.tick_params(axis="x", labelbottom=False)
ax_histy.tick_params(axis="y", labelleft=False)
# the scatter plot:
ax.scatter(x, y)
# 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')
# %%
# Defining the Axes positions using subplot_mosaic
# ------------------------------------------------
#
# We use the `~.pyplot.subplot_mosaic` function to define the positions and
# names of the three axes; the empty axes is specified by ``'.'``. We manually
# specify the size of the figure, and can make the different axes have
# different sizes by specifying the *width_ratios* and *height_ratios*
# arguments. The *layout* argument is set to ``'constrained'`` to optimize the
# spacing between the axes.
fig, axs = plt.subplot_mosaic([['histx', '.'],
['scatter', 'histy']],
figsize=(6, 6),
width_ratios=(4, 1), height_ratios=(1, 4),
layout='constrained')
scatter_hist(x, y, axs['scatter'], axs['histx'], axs['histy'])
# %%
#
# Defining the Axes positions using inset_axes
# --------------------------------------------
#
# `~.Axes.inset_axes` can be used to position marginals *outside* the main
# Axes. The advantage of doing so is that the aspect ratio of the main Axes
# can be fixed, and the marginals will always be drawn relative to the position
# of the Axes.
# Create a Figure, which doesn't have to be square.
fig = plt.figure(layout='constrained')
# Create the main Axes.
ax = fig.add_subplot()
# The main Axes' aspect can be fixed.
ax.set_aspect('equal')
# Create marginal Axes, which have 25% of the size of the main Axes. Note that
# the inset Axes are positioned *outside* (on the right and the top) of the
# main Axes, by specifying axes coordinates greater than 1. Axes coordinates
# less than 0 would likewise specify positions on the left and the bottom of
# the main Axes.
ax_histx = ax.inset_axes([0, 1.05, 1, 0.25], sharex=ax)
ax_histy = ax.inset_axes([1.05, 0, 0.25, 1], sharey=ax)
# Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)
plt.show()
# %%
#
# While we recommend using one of the two methods described above, there are
# number of other ways to achieve a similar layout:
#
# - The Axes can be positioned manually in relative coordinates using
# `~matplotlib.figure.Figure.add_axes`.
# - A gridspec can be used to create the layout
# (`~matplotlib.figure.Figure.add_gridspec`) and adding only the three desired
# axes (`~matplotlib.figure.Figure.add_subplot`).
# - Four subplots can be created using `~.pyplot.subplots`, and the unused
# axes in the upper right can be removed manually.
# - The ``axes_grid1`` toolkit can be used, as shown in
# :doc:`/gallery/axes_grid1/scatter_hist_locatable_axes`.
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.figure.Figure.subplot_mosaic`
# - `matplotlib.pyplot.subplot_mosaic`
# - `matplotlib.figure.Figure.add_subplot`
# - `matplotlib.axes.Axes.inset_axes`
# - `matplotlib.axes.Axes.scatter`
# - `matplotlib.axes.Axes.hist`
#
# .. tags::
#
# component: axes
# plot-type: scatter
# plot-type: histogram
# level: intermediate
| stable__gallery__lines_bars_and_markers__scatter_hist | 0 | figure_000.png | Scatter plot with histograms — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/scatter_hist.html#sphx-glr-download-gallery-lines-bars-and-markers-scatter-hist-py | https://matplotlib.org/stable/_downloads/3e1134ffd2662d0ad0c453c6dfb7882d/scatter_hist.py | scatter_hist.py | lines_bars_and_markers | ok | 2 | null | |
"""
============================
Scatter plot with histograms
============================
Add histograms to the x-axes and y-axes margins of a scatter plot.
This layout features a central scatter plot illustrating the relationship
between x and y, a histogram at the top displaying the distribution of x, and a
histogram on the right showing the distribution of y.
For a nice alignment of the main Axes with the marginals, two options are shown
below:
.. contents::
:local:
While `.Axes.inset_axes` may be a bit more complex, it allows correct handling
of main Axes with a fixed aspect ratio.
Let us first define a function that takes x and y data as input, as well as
three Axes, the main Axes for the scatter, and two marginal Axes. It will then
create the scatter and histograms inside the provided Axes.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
# some random data
x = np.random.randn(1000)
y = np.random.randn(1000)
def scatter_hist(x, y, ax, ax_histx, ax_histy):
# no labels
ax_histx.tick_params(axis="x", labelbottom=False)
ax_histy.tick_params(axis="y", labelleft=False)
# the scatter plot:
ax.scatter(x, y)
# 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')
# %%
# Defining the Axes positions using subplot_mosaic
# ------------------------------------------------
#
# We use the `~.pyplot.subplot_mosaic` function to define the positions and
# names of the three axes; the empty axes is specified by ``'.'``. We manually
# specify the size of the figure, and can make the different axes have
# different sizes by specifying the *width_ratios* and *height_ratios*
# arguments. The *layout* argument is set to ``'constrained'`` to optimize the
# spacing between the axes.
fig, axs = plt.subplot_mosaic([['histx', '.'],
['scatter', 'histy']],
figsize=(6, 6),
width_ratios=(4, 1), height_ratios=(1, 4),
layout='constrained')
scatter_hist(x, y, axs['scatter'], axs['histx'], axs['histy'])
# %%
#
# Defining the Axes positions using inset_axes
# --------------------------------------------
#
# `~.Axes.inset_axes` can be used to position marginals *outside* the main
# Axes. The advantage of doing so is that the aspect ratio of the main Axes
# can be fixed, and the marginals will always be drawn relative to the position
# of the Axes.
# Create a Figure, which doesn't have to be square.
fig = plt.figure(layout='constrained')
# Create the main Axes.
ax = fig.add_subplot()
# The main Axes' aspect can be fixed.
ax.set_aspect('equal')
# Create marginal Axes, which have 25% of the size of the main Axes. Note that
# the inset Axes are positioned *outside* (on the right and the top) of the
# main Axes, by specifying axes coordinates greater than 1. Axes coordinates
# less than 0 would likewise specify positions on the left and the bottom of
# the main Axes.
ax_histx = ax.inset_axes([0, 1.05, 1, 0.25], sharex=ax)
ax_histy = ax.inset_axes([1.05, 0, 0.25, 1], sharey=ax)
# Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)
plt.show()
# %%
#
# While we recommend using one of the two methods described above, there are
# number of other ways to achieve a similar layout:
#
# - The Axes can be positioned manually in relative coordinates using
# `~matplotlib.figure.Figure.add_axes`.
# - A gridspec can be used to create the layout
# (`~matplotlib.figure.Figure.add_gridspec`) and adding only the three desired
# axes (`~matplotlib.figure.Figure.add_subplot`).
# - Four subplots can be created using `~.pyplot.subplots`, and the unused
# axes in the upper right can be removed manually.
# - The ``axes_grid1`` toolkit can be used, as shown in
# :doc:`/gallery/axes_grid1/scatter_hist_locatable_axes`.
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.figure.Figure.subplot_mosaic`
# - `matplotlib.pyplot.subplot_mosaic`
# - `matplotlib.figure.Figure.add_subplot`
# - `matplotlib.axes.Axes.inset_axes`
# - `matplotlib.axes.Axes.scatter`
# - `matplotlib.axes.Axes.hist`
#
# .. tags::
#
# component: axes
# plot-type: scatter
# plot-type: histogram
# level: intermediate
| stable__gallery__lines_bars_and_markers__scatter_hist | 1 | figure_001.png | Scatter plot with histograms — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/scatter_hist.html#sphx-glr-download-gallery-lines-bars-and-markers-scatter-hist-py | https://matplotlib.org/stable/_downloads/3e1134ffd2662d0ad0c453c6dfb7882d/scatter_hist.py | scatter_hist.py | lines_bars_and_markers | ok | 2 | null | |
"""
===============================
Scatter plot with masked values
===============================
Mask some data points and add a line demarking
masked regions.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
N = 100
r0 = 0.6
x = 0.9 * np.random.rand(N)
y = 0.9 * np.random.rand(N)
area = (20 * np.random.rand(N))**2 # 0 to 10 point radii
c = np.sqrt(area)
r = np.sqrt(x ** 2 + y ** 2)
area1 = np.ma.masked_where(r < r0, area)
area2 = np.ma.masked_where(r >= r0, area)
plt.scatter(x, y, s=area1, marker='^', c=c)
plt.scatter(x, y, s=area2, marker='o', c=c)
# Show the boundary between the regions:
theta = np.arange(0, np.pi / 2, 0.01)
plt.plot(r0 * np.cos(theta), r0 * np.sin(theta))
plt.show()
# %%
# .. tags::
#
# component: marker
# plot-type: scatter
# level: beginner
| stable__gallery__lines_bars_and_markers__scatter_masked | 0 | figure_000.png | Scatter plot with masked values — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/scatter_masked.html#sphx-glr-download-gallery-lines-bars-and-markers-scatter-masked-py | https://matplotlib.org/stable/_downloads/68d80e3d1e3f3561a71b3e5c8efae907/scatter_masked.py | scatter_masked.py | lines_bars_and_markers | ok | 1 | null | |
"""
===============
Marker examples
===============
Example with different ways to specify markers.
See also the `matplotlib.markers` documentation for a list of all markers and
:doc:`/gallery/lines_bars_and_markers/marker_reference` for more information
on configuring markers.
.. redirect-from:: /gallery/lines_bars_and_markers/scatter_custom_symbol
.. redirect-from:: /gallery/lines_bars_and_markers/scatter_symbol
.. redirect-from:: /gallery/lines_bars_and_markers/scatter_piecharts
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.rand(10)
y = np.random.rand(10)
z = np.sqrt(x**2 + y**2)
fig, axs = plt.subplots(2, 3, sharex=True, sharey=True, layout="constrained")
# Matplotlib marker symbol
axs[0, 0].scatter(x, y, s=80, c=z, marker=">")
axs[0, 0].set_title("marker='>'")
# marker from TeX: passing a TeX symbol name enclosed in $-signs
axs[0, 1].scatter(x, y, s=80, c=z, marker=r"$\clubsuit$")
axs[0, 1].set_title(r"marker=r'\$\clubsuit\$'")
# marker from path: passing a custom path of N vertices as a (N, 2) array-like
verts = [[-1, -1], [1, -1], [1, 1], [-1, -1]]
axs[0, 2].scatter(x, y, s=80, c=z, marker=verts)
axs[0, 2].set_title("marker=verts")
# regular pentagon marker
axs[1, 0].scatter(x, y, s=80, c=z, marker=(5, 0))
axs[1, 0].set_title("marker=(5, 0)")
# regular 5-pointed star marker
axs[1, 1].scatter(x, y, s=80, c=z, marker=(5, 1))
axs[1, 1].set_title("marker=(5, 1)")
# regular 5-pointed asterisk marker
axs[1, 2].scatter(x, y, s=80, c=z, marker=(5, 2))
axs[1, 2].set_title("marker=(5, 2)")
plt.show()
# %%
# .. tags::
#
# component: marker
# level: beginner
| stable__gallery__lines_bars_and_markers__scatter_star_poly | 0 | figure_000.png | Marker examples — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/scatter_star_poly.html#sphx-glr-download-gallery-lines-bars-and-markers-scatter-star-poly-py | https://matplotlib.org/stable/_downloads/bec52923c4e8bde35b6455fdff6def07/scatter_star_poly.py | scatter_star_poly.py | lines_bars_and_markers | ok | 1 | null | |
"""
==========================
Scatter plot with a legend
==========================
To create a scatter plot with a legend one may use a loop and create one
`~.Axes.scatter` plot per item to appear in the legend and set the ``label``
accordingly.
The following also demonstrates how transparency of the markers
can be adjusted by giving ``alpha`` a value between 0 and 1.
"""
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
fig, ax = plt.subplots()
for color in ['tab:blue', 'tab:orange', 'tab:green']:
n = 750
x, y = np.random.rand(2, n)
scale = 200.0 * np.random.rand(n)
ax.scatter(x, y, c=color, s=scale, label=color,
alpha=0.3, edgecolors='none')
ax.legend()
ax.grid(True)
plt.show()
# %%
# .. _automatedlegendcreation:
#
# Automated legend creation
# -------------------------
#
# Another option for creating a legend for a scatter is to use the
# `.PathCollection.legend_elements` method. It will automatically try to
# determine a useful number of legend entries to be shown and return a tuple of
# handles and labels. Those can be passed to the call to `~.axes.Axes.legend`.
N = 45
x, y = np.random.rand(2, N)
c = np.random.randint(1, 5, size=N)
s = np.random.randint(10, 220, size=N)
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, c=c, s=s)
# produce a legend with the unique colors from the scatter
legend1 = ax.legend(*scatter.legend_elements(),
loc="lower left", title="Classes")
ax.add_artist(legend1)
# produce a legend with a cross-section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes")
plt.show()
# %%
# Further arguments to the `.PathCollection.legend_elements` method
# can be used to steer how many legend entries are to be created and how they
# should be labeled. The following shows how to use some of them.
volume = np.random.rayleigh(27, size=40)
amount = np.random.poisson(10, size=40)
ranking = np.random.normal(size=40)
price = np.random.uniform(1, 10, size=40)
fig, ax = plt.subplots()
# Because the price is much too small when being provided as size for ``s``,
# we normalize it to some useful point sizes, s=0.3*(price*3)**2
scatter = ax.scatter(volume, amount, c=ranking, s=0.3*(price*3)**2,
vmin=-3, vmax=3, cmap="Spectral")
# Produce a legend for the ranking (colors). Even though there are 40 different
# rankings, we only want to show 5 of them in the legend.
legend1 = ax.legend(*scatter.legend_elements(num=5),
loc="upper left", title="Ranking")
ax.add_artist(legend1)
# Produce a legend for the price (sizes). Because we want to show the prices
# in dollars, we use the *func* argument to supply the inverse of the function
# used to calculate the sizes from above. The *fmt* ensures to show the price
# in dollars. Note how we target at 5 elements here, but obtain only 4 in the
# created legend due to the automatic round prices that are chosen for us.
kw = dict(prop="sizes", num=5, color=scatter.cmap(0.7), fmt="$ {x:.2f}",
func=lambda s: np.sqrt(s/.3)/3)
legend2 = ax.legend(*scatter.legend_elements(**kw),
loc="lower right", title="Price")
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.scatter` / `matplotlib.pyplot.scatter`
# - `matplotlib.axes.Axes.legend` / `matplotlib.pyplot.legend`
# - `matplotlib.collections.PathCollection.legend_elements`
#
# .. tags::
#
# component: legend
# plot-type: scatter
# level: intermediate
| stable__gallery__lines_bars_and_markers__scatter_with_legend | 0 | figure_000.png | Scatter plot with a legend — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/scatter_with_legend.html#sphx-glr-download-gallery-lines-bars-and-markers-scatter-with-legend-py | https://matplotlib.org/stable/_downloads/e296fc40ba715311fdebebae0ecf1c71/scatter_with_legend.py | scatter_with_legend.py | lines_bars_and_markers | ok | 3 | null | |
"""
=========
Line plot
=========
Create a basic line plot.
"""
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
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`
# - `matplotlib.pyplot.subplots`
# - `matplotlib.figure.Figure.savefig`
#
# .. tags::
#
# plot-style: line
# level: beginner
| stable__gallery__lines_bars_and_markers__simple_plot | 0 | figure_000.png | Line plot — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/simple_plot.html#sphx-glr-download-gallery-lines-bars-and-markers-simple-plot-py | https://matplotlib.org/stable/_downloads/841352d8ea6065fce570abdf6225ef02/simple_plot.py | simple_plot.py | lines_bars_and_markers | ok | 1 | null | |
"""
==========================================================
Shade regions defined by a logical mask using fill_between
==========================================================
"""
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2, 0.01)
s = np.sin(2*np.pi*t)
fig, ax = plt.subplots()
ax.plot(t, s, color='black')
ax.axhline(0, color='black')
ax.fill_between(t, 1, where=s > 0, facecolor='green', alpha=.5)
ax.fill_between(t, -1, where=s < 0, facecolor='red', alpha=.5)
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.fill_between`
#
# .. tags::
#
# styling: conditional
# plot-style: fill_between
# level: beginner
| stable__gallery__lines_bars_and_markers__span_regions | 0 | figure_000.png | Shade regions defined by a logical mask using fill_between — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/span_regions.html#sphx-glr-download-gallery-lines-bars-and-markers-span-regions-py | https://matplotlib.org/stable/_downloads/ae69400014c751155c2d298248eb41e6/span_regions.py | span_regions.py | lines_bars_and_markers | ok | 1 | null | |
"""
========================
Spectrum representations
========================
The plots show different spectrum representations of a sine signal with
additive noise. A (frequency) spectrum of a discrete-time signal is calculated
by utilizing the fast Fourier transform (FFT).
"""
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
dt = 0.01 # sampling interval
Fs = 1 / dt # sampling frequency
t = np.arange(0, 10, dt)
# generate noise:
nse = np.random.randn(len(t))
r = np.exp(-t / 0.05)
cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
s = 0.1 * np.sin(4 * np.pi * t) + cnse # the signal
fig = plt.figure(figsize=(7, 7), layout='constrained')
axs = fig.subplot_mosaic([["signal", "signal"],
["magnitude", "log_magnitude"],
["phase", "angle"]])
# plot time signal:
axs["signal"].set_title("Signal")
axs["signal"].plot(t, s, color='C0')
axs["signal"].set_xlabel("Time (s)")
axs["signal"].set_ylabel("Amplitude")
# plot different spectrum types:
axs["magnitude"].set_title("Magnitude Spectrum")
axs["magnitude"].magnitude_spectrum(s, Fs=Fs, color='C1')
axs["log_magnitude"].set_title("Log. Magnitude Spectrum")
axs["log_magnitude"].magnitude_spectrum(s, Fs=Fs, scale='dB', color='C1')
axs["phase"].set_title("Phase Spectrum ")
axs["phase"].phase_spectrum(s, Fs=Fs, color='C2')
axs["angle"].set_title("Angle Spectrum")
axs["angle"].angle_spectrum(s, Fs=Fs, color='C2')
plt.show()
# %%
# .. tags::
#
# domain: signal-processing
# plot-type: line
# level: beginner
| stable__gallery__lines_bars_and_markers__spectrum_demo | 0 | figure_000.png | Spectrum representations — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/spectrum_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-spectrum-demo-py | https://matplotlib.org/stable/_downloads/b8c57e62999229824f455e779d286772/spectrum_demo.py | spectrum_demo.py | lines_bars_and_markers | ok | 1 | null | |
"""
===========================
Stackplots and streamgraphs
===========================
"""
# %%
# Stackplots
# ----------
#
# Stackplots draw multiple datasets as vertically stacked areas. This is
# useful when the individual data values and additionally their cumulative
# value are of interest.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mticker
# data from United Nations World Population Prospects (Revision 2019)
# https://population.un.org/wpp/, license: CC BY 3.0 IGO
year = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2018]
population_by_continent = {
'Africa': [.228, .284, .365, .477, .631, .814, 1.044, 1.275],
'the Americas': [.340, .425, .519, .619, .727, .840, .943, 1.006],
'Asia': [1.394, 1.686, 2.120, 2.625, 3.202, 3.714, 4.169, 4.560],
'Europe': [.220, .253, .276, .295, .310, .303, .294, .293],
'Oceania': [.012, .015, .019, .022, .026, .031, .036, .039],
}
fig, ax = plt.subplots()
ax.stackplot(year, population_by_continent.values(),
labels=population_by_continent.keys(), alpha=0.8)
ax.legend(loc='upper left', reverse=True)
ax.set_title('World population')
ax.set_xlabel('Year')
ax.set_ylabel('Number of people (billions)')
# add tick at every 200 million people
ax.yaxis.set_minor_locator(mticker.MultipleLocator(.2))
plt.show()
# %%
# Streamgraphs
# ------------
#
# Using the *baseline* parameter, you can turn an ordinary stacked area plot
# with baseline 0 into a stream graph.
# Fixing random state for reproducibility
np.random.seed(19680801)
def gaussian_mixture(x, n=5):
"""Return a random mixture of *n* Gaussians, evaluated at positions *x*."""
def add_random_gaussian(a):
amplitude = 1 / (.1 + np.random.random())
dx = x[-1] - x[0]
x0 = (2 * np.random.random() - .5) * dx
z = 10 / (.1 + np.random.random()) / dx
a += amplitude * np.exp(-(z * (x - x0))**2)
a = np.zeros_like(x)
for j in range(n):
add_random_gaussian(a)
return a
x = np.linspace(0, 100, 101)
ys = [gaussian_mixture(x) for _ in range(3)]
fig, ax = plt.subplots()
ax.stackplot(x, ys, baseline='wiggle')
plt.show()
# %%
# .. tags::
#
# plot-type: stackplot
# level: intermediate
| stable__gallery__lines_bars_and_markers__stackplot_demo | 0 | figure_000.png | Stackplots and streamgraphs — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/stackplot_demo.html#streamgraphs | https://matplotlib.org/stable/_downloads/a4ca2d398a778f09d428679d85cdef43/stackplot_demo.py | stackplot_demo.py | lines_bars_and_markers | ok | 2 | null | |
"""
===========
Stairs Demo
===========
This example demonstrates the use of `~.matplotlib.pyplot.stairs` for stepwise
constant functions. A common use case is histogram and histogram-like data
visualization.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import StepPatch
np.random.seed(0)
h, edges = np.histogram(np.random.normal(5, 3, 5000),
bins=np.linspace(0, 10, 20))
fig, axs = plt.subplots(3, 1, figsize=(7, 15))
axs[0].stairs(h, edges, label='Simple histogram')
axs[0].stairs(h, edges + 5, baseline=50, label='Modified baseline')
axs[0].stairs(h, edges + 10, baseline=None, label='No edges')
axs[0].set_title("Step Histograms")
axs[1].stairs(np.arange(1, 6, 1), fill=True,
label='Filled histogram\nw/ automatic edges')
axs[1].stairs(np.arange(1, 6, 1)*0.3, np.arange(2, 8, 1),
orientation='horizontal', hatch='//',
label='Hatched histogram\nw/ horizontal orientation')
axs[1].set_title("Filled histogram")
patch = StepPatch(values=[1, 2, 3, 2, 1],
edges=range(1, 7),
label=('Patch derived underlying object\n'
'with default edge/facecolor behaviour'))
axs[2].add_patch(patch)
axs[2].set_xlim(0, 7)
axs[2].set_ylim(-1, 5)
axs[2].set_title("StepPatch artist")
for ax in axs:
ax.legend()
plt.show()
# %%
# *baseline* can take an array to allow for stacked histogram plots
A = [[0, 0, 0],
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]]
for i in range(len(A) - 1):
plt.stairs(A[i+1], baseline=A[i], fill=True)
# %%
# Comparison of `.pyplot.step` and `.pyplot.stairs`
# -------------------------------------------------
#
# `.pyplot.step` defines the positions of the steps as single values. The steps
# extend left/right/both ways from these reference values depending on the
# parameter *where*. The number of *x* and *y* values is the same.
#
# In contrast, `.pyplot.stairs` defines the positions of the steps via their
# bounds *edges*, which is one element longer than the step values.
bins = np.arange(14)
centers = bins[:-1] + np.diff(bins) / 2
y = np.sin(centers / 2)
plt.step(bins[:-1], y, where='post', label='step(where="post")')
plt.plot(bins[:-1], y, 'o--', color='grey', alpha=0.3)
plt.stairs(y - 1, bins, baseline=None, label='stairs()')
plt.plot(centers, y - 1, 'o--', color='grey', alpha=0.3)
plt.plot(np.repeat(bins, 2), np.hstack([y[0], np.repeat(y, 2), y[-1]]) - 1,
'o', color='red', alpha=0.2)
plt.legend()
plt.title('step() vs. stairs()')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.stairs` / `matplotlib.pyplot.stairs`
# - `matplotlib.patches.StepPatch`
#
# .. tags::
#
# plot-type: stairs
# level: intermediate
| stable__gallery__lines_bars_and_markers__stairs_demo | 0 | figure_000.png | Stairs Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/stairs_demo.html#stairs-demo | https://matplotlib.org/stable/_downloads/99b2228ef8ead5b15771558e042ee4f3/stairs_demo.py | stairs_demo.py | lines_bars_and_markers | ok | 2 | null | |
"""
=========
Stem plot
=========
`~.pyplot.stem` plots vertical lines from a baseline to the y-coordinate and
places a marker at the tip.
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 2 * np.pi, 41)
y = np.exp(np.sin(x))
plt.stem(x, y)
plt.show()
# %%
#
# The position of the baseline can be adapted using *bottom*.
# The parameters *linefmt*, *markerfmt*, and *basefmt* control basic format
# properties of the plot. However, in contrast to `~.pyplot.plot` not all
# properties are configurable via keyword arguments. For more advanced
# control adapt the line objects returned by `.pyplot`.
markerline, stemlines, baseline = plt.stem(
x, y, linefmt='grey', markerfmt='D', bottom=1.1)
markerline.set_markerfacecolor('none')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.stem` / `matplotlib.pyplot.stem`
#
# .. tags::
#
# plot-type: stem
# level: beginner
| stable__gallery__lines_bars_and_markers__stem_plot | 0 | figure_000.png | Stem plot — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/stem_plot.html#stem-plot | https://matplotlib.org/stable/_downloads/605cad767f8ac8bf813bcd4941015322/stem_plot.py | stem_plot.py | lines_bars_and_markers | ok | 2 | null | |
"""
=========
Step Demo
=========
This example demonstrates the use of `.pyplot.step` for piece-wise constant
curves. In particular, it illustrates the effect of the parameter *where*
on the step position.
.. note::
For the common case that you know the edge positions, use `.pyplot.stairs`
instead.
The circular markers created with `.pyplot.plot` show the actual data
positions so that it's easier to see the effect of *where*.
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(14)
y = np.sin(x / 2)
plt.step(x, y + 2, label='pre (default)')
plt.plot(x, y + 2, 'o--', color='grey', alpha=0.3)
plt.step(x, y + 1, where='mid', label='mid')
plt.plot(x, y + 1, 'o--', color='grey', alpha=0.3)
plt.step(x, y, where='post', label='post')
plt.plot(x, y, 'o--', color='grey', alpha=0.3)
plt.grid(axis='x', color='0.95')
plt.legend(title='Parameter where:')
plt.title('plt.step(where=...)')
plt.show()
# %%
# The same behavior can be achieved by using the ``drawstyle`` parameter of
# `.pyplot.plot`.
plt.plot(x, y + 2, drawstyle='steps', label='steps (=steps-pre)')
plt.plot(x, y + 2, 'o--', color='grey', alpha=0.3)
plt.plot(x, y + 1, drawstyle='steps-mid', label='steps-mid')
plt.plot(x, y + 1, 'o--', color='grey', alpha=0.3)
plt.plot(x, y, drawstyle='steps-post', label='steps-post')
plt.plot(x, y, 'o--', color='grey', alpha=0.3)
plt.grid(axis='x', color='0.95')
plt.legend(title='Parameter drawstyle:')
plt.title('plt.plot(drawstyle=...)')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.step` / `matplotlib.pyplot.step`
# - `matplotlib.axes.Axes.plot` / `matplotlib.pyplot.plot`
#
# .. tags::
#
# plot-type: step
# plot-type: line
# level: beginner
| stable__gallery__lines_bars_and_markers__step_demo | 0 | figure_000.png | Step Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/step_demo.html#step-demo | https://matplotlib.org/stable/_downloads/f8a42a328abce5e8455725246cb68710/step_demo.py | step_demo.py | lines_bars_and_markers | ok | 2 | null | |
"""
====================================
Timeline with lines, dates, and text
====================================
How to create a simple timeline using Matplotlib release dates.
Timelines can be created with a collection of dates and text. In this example,
we show how to create a simple timeline using the dates for recent releases
of Matplotlib. First, we'll pull the data from GitHub.
"""
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
try:
# Try to fetch a list of Matplotlib releases and their dates
# from https://api.github.com/repos/matplotlib/matplotlib/releases
import json
import urllib.request
url = 'https://api.github.com/repos/matplotlib/matplotlib/releases'
url += '?per_page=100'
data = json.loads(urllib.request.urlopen(url, timeout=1).read().decode())
dates = []
releases = []
for item in data:
if 'rc' not in item['tag_name'] and 'b' not in item['tag_name']:
dates.append(item['published_at'].split("T")[0])
releases.append(item['tag_name'].lstrip("v"))
except Exception:
# In case the above fails, e.g. because of missing internet connection
# use the following lists as fallback.
releases = ['2.2.4', '3.0.3', '3.0.2', '3.0.1', '3.0.0', '2.2.3',
'2.2.2', '2.2.1', '2.2.0', '2.1.2', '2.1.1', '2.1.0',
'2.0.2', '2.0.1', '2.0.0', '1.5.3', '1.5.2', '1.5.1',
'1.5.0', '1.4.3', '1.4.2', '1.4.1', '1.4.0']
dates = ['2019-02-26', '2019-02-26', '2018-11-10', '2018-11-10',
'2018-09-18', '2018-08-10', '2018-03-17', '2018-03-16',
'2018-03-06', '2018-01-18', '2017-12-10', '2017-10-07',
'2017-05-10', '2017-05-02', '2017-01-17', '2016-09-09',
'2016-07-03', '2016-01-10', '2015-10-29', '2015-02-16',
'2014-10-26', '2014-10-18', '2014-08-26']
dates = [datetime.strptime(d, "%Y-%m-%d") for d in dates] # Convert strs to dates.
releases = [tuple(release.split('.')) for release in releases] # Split by component.
dates, releases = zip(*sorted(zip(dates, releases))) # Sort by increasing date.
# %%
# Next, we'll create a stem plot with some variation in levels as to
# distinguish even close-by events. We add markers on the baseline for visual
# emphasis on the one-dimensional nature of the timeline.
#
# For each event, we add a text label via `~.Axes.annotate`, which is offset
# in units of points from the tip of the event line.
#
# Note that Matplotlib will automatically plot datetime inputs.
# Choose some nice levels: alternate meso releases between top and bottom, and
# progressively shorten the stems for micro releases.
levels = []
macro_meso_releases = sorted({release[:2] for release in releases})
for release in releases:
macro_meso = release[:2]
micro = int(release[2])
h = 1 + 0.8 * (5 - micro)
level = h if macro_meso_releases.index(macro_meso) % 2 == 0 else -h
levels.append(level)
def is_feature(release):
"""Return whether a version (split into components) is a feature release."""
return release[-1] == '0'
# The figure and the axes.
fig, ax = plt.subplots(figsize=(8.8, 4), layout="constrained")
ax.set(title="Matplotlib release dates")
# The vertical stems.
ax.vlines(dates, 0, levels,
color=[("tab:red", 1 if is_feature(release) else .5) for release in releases])
# The baseline.
ax.axhline(0, c="black")
# The markers on the baseline.
meso_dates = [date for date, release in zip(dates, releases) if is_feature(release)]
micro_dates = [date for date, release in zip(dates, releases)
if not is_feature(release)]
ax.plot(micro_dates, np.zeros_like(micro_dates), "ko", mfc="white")
ax.plot(meso_dates, np.zeros_like(meso_dates), "ko", mfc="tab:red")
# Annotate the lines.
for date, level, release in zip(dates, levels, releases):
version_str = '.'.join(release)
ax.annotate(version_str, xy=(date, level),
xytext=(-3, np.sign(level)*3), textcoords="offset points",
verticalalignment="bottom" if level > 0 else "top",
weight="bold" if is_feature(release) else "normal",
bbox=dict(boxstyle='square', pad=0, lw=0, fc=(1, 1, 1, 0.7)))
ax.xaxis.set(major_locator=mdates.YearLocator(),
major_formatter=mdates.DateFormatter("%Y"))
# Remove the y-axis and some spines.
ax.yaxis.set_visible(False)
ax.spines[["left", "top", "right"]].set_visible(False)
ax.margins(y=0.1)
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.annotate`
# - `matplotlib.axes.Axes.vlines`
# - `matplotlib.axis.Axis.set_major_locator`
# - `matplotlib.axis.Axis.set_major_formatter`
# - `matplotlib.dates.MonthLocator`
# - `matplotlib.dates.DateFormatter`
#
# .. tags::
#
# component: annotate
# plot-type: line
# level: intermediate
| stable__gallery__lines_bars_and_markers__timeline | 0 | figure_000.png | Timeline with lines, dates, and text — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/timeline.html#timeline-with-lines-dates-and-text | https://matplotlib.org/stable/_downloads/e4e3bbd0b1c82e93b916e64bd632f7a9/timeline.py | timeline.py | lines_bars_and_markers | ok | 1 | null | |
"""
=================
hlines and vlines
=================
This example showcases the functions hlines and vlines.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
t = np.arange(0.0, 5.0, 0.1)
s = np.exp(-t) + np.sin(2 * np.pi * t) + 1
nse = np.random.normal(0.0, 0.3, t.shape) * s
fig, (vax, hax) = plt.subplots(1, 2, figsize=(12, 6))
vax.plot(t, s + nse, '^')
vax.vlines(t, [0], s)
# By using ``transform=vax.get_xaxis_transform()`` the y coordinates are scaled
# such that 0 maps to the bottom of the Axes and 1 to the top.
vax.vlines([1, 2], 0, 1, transform=vax.get_xaxis_transform(), colors='r')
vax.set_xlabel('time (s)')
vax.set_title('Vertical lines demo')
hax.plot(s + nse, t, '^')
hax.hlines(t, [0], s, lw=2)
hax.set_xlabel('time (s)')
hax.set_title('Horizontal lines demo')
plt.show()
# %%
# .. tags::
#
# plot-type: line
# level: beginner
| stable__gallery__lines_bars_and_markers__vline_hline_demo | 0 | figure_000.png | hlines and vlines — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/vline_hline_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-vline-hline-demo-py | https://matplotlib.org/stable/_downloads/fcbc14b23962009bcf6e5a7d52e939c8/vline_hline_demo.py | vline_hline_demo.py | lines_bars_and_markers | ok | 1 | null | |
"""
===========================
Cross- and auto-correlation
===========================
Example use of cross-correlation (`~.Axes.xcorr`) and auto-correlation
(`~.Axes.acorr`) plots.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
x, y = np.random.randn(2, 100)
fig, [ax1, ax2] = plt.subplots(2, 1, sharex=True)
ax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2)
ax1.grid(True)
ax1.set_title('Cross-correlation (xcorr)')
ax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2)
ax2.grid(True)
ax2.set_title('Auto-correlation (acorr)')
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.axes.Axes.acorr` / `matplotlib.pyplot.acorr`
# - `matplotlib.axes.Axes.xcorr` / `matplotlib.pyplot.xcorr`
#
# .. tags::
#
# domain: statistics
# level: beginner
| stable__gallery__lines_bars_and_markers__xcorr_acorr_demo | 0 | figure_000.png | Cross- and auto-correlation — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/lines_bars_and_markers/xcorr_acorr_demo.html#sphx-glr-download-gallery-lines-bars-and-markers-xcorr-acorr-demo-py | https://matplotlib.org/stable/_downloads/fad6b154bf9cffbaaac152da639e6889/xcorr_acorr_demo.py | xcorr_acorr_demo.py | lines_bars_and_markers | ok | 1 | null | |
"""
================
Anchored Artists
================
This example illustrates the use of the anchored objects without the
helper classes found in :mod:`mpl_toolkits.axes_grid1`. This version
of the figure is similar to the one found in
:doc:`/gallery/axes_grid1/simple_anchored_artists`, but it is
implemented using only the matplotlib namespace, without the help
of additional toolkits.
.. redirect-from:: /gallery/userdemo/anchored_box01
.. redirect-from:: /gallery/userdemo/anchored_box02
.. redirect-from:: /gallery/userdemo/anchored_box03
"""
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox,
DrawingArea, TextArea, VPacker)
from matplotlib.patches import Circle, Ellipse
def draw_text(ax):
"""Draw a text-box anchored to the upper-left corner of the figure."""
box = AnchoredOffsetbox(child=TextArea("Figure 1a"),
loc="upper left", frameon=True)
box.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(box)
def draw_circles(ax):
"""Draw circles in axes coordinates."""
area = DrawingArea(width=40, height=20)
area.add_artist(Circle((10, 10), 10, fc="tab:blue"))
area.add_artist(Circle((30, 10), 5, fc="tab:red"))
box = AnchoredOffsetbox(
child=area, loc="upper right", pad=0, frameon=False)
ax.add_artist(box)
def draw_ellipse(ax):
"""Draw an ellipse of width=0.1, height=0.15 in data coordinates."""
aux_tr_box = AuxTransformBox(ax.transData)
aux_tr_box.add_artist(Ellipse((0, 0), width=0.1, height=0.15))
box = AnchoredOffsetbox(child=aux_tr_box, loc="lower left", frameon=True)
ax.add_artist(box)
def draw_sizebar(ax):
"""
Draw a horizontal bar with length of 0.1 in data coordinates,
with a fixed label center-aligned underneath.
"""
size = 0.1
text = r"1$^{\prime}$"
sizebar = AuxTransformBox(ax.transData)
sizebar.add_artist(Line2D([0, size], [0, 0], color="black"))
text = TextArea(text)
packer = VPacker(
children=[sizebar, text], align="center", sep=5) # separation in points.
ax.add_artist(AnchoredOffsetbox(
child=packer, loc="lower center", frameon=False,
pad=0.1, borderpad=0.5)) # paddings relative to the legend fontsize.
fig, ax = plt.subplots()
ax.set_aspect(1)
draw_text(ax)
draw_circles(ax)
draw_ellipse(ax)
draw_sizebar(ax)
plt.show()
| stable__gallery__misc__anchored_artists | 0 | figure_000.png | Anchored Artists — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/anchored_artists.html#sphx-glr-download-gallery-misc-anchored-artists-py | https://matplotlib.org/stable/_downloads/56dd8a42c5506d6f4b030f191ab55a38/anchored_artists.py | anchored_artists.py | misc | ok | 1 | null | |
"""
==================================
Identify whether artists intersect
==================================
The lines intersecting the rectangle are colored in red, while the others
are left as blue lines. This example showcases the `.intersects_bbox` function.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.path import Path
from matplotlib.transforms import Bbox
# Fixing random state for reproducibility
np.random.seed(19680801)
left, bottom, width, height = (-1, -1, 2, 2)
rect = plt.Rectangle((left, bottom), width, height,
facecolor="black", alpha=0.1)
fig, ax = plt.subplots()
ax.add_patch(rect)
bbox = Bbox.from_bounds(left, bottom, width, height)
for i in range(12):
vertices = (np.random.random((2, 2)) - 0.5) * 6.0
path = Path(vertices)
if path.intersects_bbox(bbox):
color = 'r'
else:
color = 'b'
ax.plot(vertices[:, 0], vertices[:, 1], color=color)
plt.show()
| stable__gallery__misc__bbox_intersect | 0 | figure_000.png | Identify whether artists intersect — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/bbox_intersect.html#sphx-glr-gallery-misc-bbox-intersect-py | https://matplotlib.org/stable/_downloads/832476b1f1a894c408ecb93acb7b935c/bbox_intersect.py | bbox_intersect.py | misc | ok | 1 | null | |
"""
==============
Manual Contour
==============
Example of displaying your own contour lines and polygons using ContourSet.
"""
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.contour import ContourSet
from matplotlib.path import Path
# %%
# Contour lines for each level are a list/tuple of polygons.
lines0 = [[[0, 0], [0, 4]]]
lines1 = [[[2, 0], [1, 2], [1, 3]]]
lines2 = [[[3, 0], [3, 2]], [[3, 3], [3, 4]]] # Note two lines.
# %%
# Filled contours between two levels are also a list/tuple of polygons.
# Points can be ordered clockwise or anticlockwise.
filled01 = [[[0, 0], [0, 4], [1, 3], [1, 2], [2, 0]]]
filled12 = [[[2, 0], [3, 0], [3, 2], [1, 3], [1, 2]], # Note two polygons.
[[1, 4], [3, 4], [3, 3]]]
# %%
fig, ax = plt.subplots()
# Filled contours using filled=True.
cs = ContourSet(ax, [0, 1, 2], [filled01, filled12], filled=True, cmap=cm.bone)
cbar = fig.colorbar(cs)
# Contour lines (non-filled).
lines = ContourSet(
ax, [0, 1, 2], [lines0, lines1, lines2], cmap=cm.cool, linewidths=3)
cbar.add_lines(lines)
ax.set(xlim=(-0.5, 3.5), ylim=(-0.5, 4.5),
title='User-specified contours')
# %%
# Multiple filled contour lines can be specified in a single list of polygon
# vertices along with a list of vertex kinds (code types) as described in the
# Path class. This is particularly useful for polygons with holes.
fig, ax = plt.subplots()
filled01 = [[[0, 0], [3, 0], [3, 3], [0, 3], [1, 1], [1, 2], [2, 2], [2, 1]]]
M = Path.MOVETO
L = Path.LINETO
kinds01 = [[M, L, L, L, M, L, L, L]]
cs = ContourSet(ax, [0, 1], [filled01], [kinds01], filled=True)
cbar = fig.colorbar(cs)
ax.set(xlim=(-0.5, 3.5), ylim=(-0.5, 3.5),
title='User specified filled contours with holes')
plt.show()
| stable__gallery__misc__contour_manual | 0 | figure_000.png | Manual Contour — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/contour_manual.html#sphx-glr-download-gallery-misc-contour-manual-py | https://matplotlib.org/stable/_downloads/6f6ddec07749bdbe4eea6b25d5dc81a6/contour_manual.py | contour_manual.py | misc | ok | 2 | null | |
"""
==============
Manual Contour
==============
Example of displaying your own contour lines and polygons using ContourSet.
"""
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.contour import ContourSet
from matplotlib.path import Path
# %%
# Contour lines for each level are a list/tuple of polygons.
lines0 = [[[0, 0], [0, 4]]]
lines1 = [[[2, 0], [1, 2], [1, 3]]]
lines2 = [[[3, 0], [3, 2]], [[3, 3], [3, 4]]] # Note two lines.
# %%
# Filled contours between two levels are also a list/tuple of polygons.
# Points can be ordered clockwise or anticlockwise.
filled01 = [[[0, 0], [0, 4], [1, 3], [1, 2], [2, 0]]]
filled12 = [[[2, 0], [3, 0], [3, 2], [1, 3], [1, 2]], # Note two polygons.
[[1, 4], [3, 4], [3, 3]]]
# %%
fig, ax = plt.subplots()
# Filled contours using filled=True.
cs = ContourSet(ax, [0, 1, 2], [filled01, filled12], filled=True, cmap=cm.bone)
cbar = fig.colorbar(cs)
# Contour lines (non-filled).
lines = ContourSet(
ax, [0, 1, 2], [lines0, lines1, lines2], cmap=cm.cool, linewidths=3)
cbar.add_lines(lines)
ax.set(xlim=(-0.5, 3.5), ylim=(-0.5, 4.5),
title='User-specified contours')
# %%
# Multiple filled contour lines can be specified in a single list of polygon
# vertices along with a list of vertex kinds (code types) as described in the
# Path class. This is particularly useful for polygons with holes.
fig, ax = plt.subplots()
filled01 = [[[0, 0], [3, 0], [3, 3], [0, 3], [1, 1], [1, 2], [2, 2], [2, 1]]]
M = Path.MOVETO
L = Path.LINETO
kinds01 = [[M, L, L, L, M, L, L, L]]
cs = ContourSet(ax, [0, 1], [filled01], [kinds01], filled=True)
cbar = fig.colorbar(cs)
ax.set(xlim=(-0.5, 3.5), ylim=(-0.5, 3.5),
title='User specified filled contours with holes')
plt.show()
| stable__gallery__misc__contour_manual | 1 | figure_001.png | Manual Contour — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/contour_manual.html#sphx-glr-download-gallery-misc-contour-manual-py | https://matplotlib.org/stable/_downloads/6f6ddec07749bdbe4eea6b25d5dc81a6/contour_manual.py | contour_manual.py | misc | ok | 2 | null | |
"""
=============
Coords Report
=============
Override the default reporting of coords as the mouse moves over the Axes
in an interactive backend.
"""
import matplotlib.pyplot as plt
import numpy as np
def millions(x):
return '$%1.1fM' % (x * 1e-6)
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.rand(20)
y = 1e7 * np.random.rand(20)
fig, ax = plt.subplots()
ax.fmt_ydata = millions
plt.plot(x, y, 'o')
plt.show()
| stable__gallery__misc__coords_report | 0 | figure_000.png | Coords Report — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/coords_report.html#sphx-glr-download-gallery-misc-coords-report-py | https://matplotlib.org/stable/_downloads/3cf562cde19e200420cb83f024dd891a/coords_report.py | coords_report.py | misc | ok | 1 | null | |
"""
=================
Custom projection
=================
Showcase Hammer projection by alleviating many features of Matplotlib.
"""
import numpy as np
import matplotlib
from matplotlib.axes import Axes
import matplotlib.axis as maxis
from matplotlib.patches import Circle
from matplotlib.path import Path
from matplotlib.projections import register_projection
import matplotlib.spines as mspines
from matplotlib.ticker import FixedLocator, Formatter, NullLocator
from matplotlib.transforms import Affine2D, BboxTransformTo, Transform
rcParams = matplotlib.rcParams
# This example projection class is rather long, but it is designed to
# illustrate many features, not all of which will be used every time.
# It is also common to factor out a lot of these methods into common
# code used by a number of projections with similar characteristics
# (see geo.py).
class GeoAxes(Axes):
"""
An abstract base class for geographic projections
"""
class ThetaFormatter(Formatter):
"""
Used to format the theta tick labels. Converts the native
unit of radians into degrees and adds a degree symbol.
"""
def __init__(self, round_to=1.0):
self._round_to = round_to
def __call__(self, x, pos=None):
degrees = round(np.rad2deg(x) / self._round_to) * self._round_to
return f"{degrees:0.0f}\N{DEGREE SIGN}"
RESOLUTION = 75
def _init_axis(self):
self.xaxis = maxis.XAxis(self)
self.yaxis = maxis.YAxis(self)
# Do not register xaxis or yaxis with spines -- as done in
# Axes._init_axis() -- until GeoAxes.xaxis.clear() works.
# self.spines['geo'].register_axis(self.yaxis)
def clear(self):
# docstring inherited
super().clear()
self.set_longitude_grid(30)
self.set_latitude_grid(15)
self.set_longitude_grid_ends(75)
self.xaxis.set_minor_locator(NullLocator())
self.yaxis.set_minor_locator(NullLocator())
self.xaxis.set_ticks_position('none')
self.yaxis.set_ticks_position('none')
self.yaxis.set_tick_params(label1On=True)
# Why do we need to turn on yaxis tick labels, but
# xaxis tick labels are already on?
self.grid(rcParams['axes.grid'])
Axes.set_xlim(self, -np.pi, np.pi)
Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)
def _set_lim_and_transforms(self):
# A (possibly non-linear) projection on the (already scaled) data
# There are three important coordinate spaces going on here:
#
# 1. Data space: The space of the data itself
#
# 2. Axes space: The unit rectangle (0, 0) to (1, 1)
# covering the entire plot area.
#
# 3. Display space: The coordinates of the resulting image,
# often in pixels or dpi/inch.
# This function makes heavy use of the Transform classes in
# ``lib/matplotlib/transforms.py.`` For more information, see
# the inline documentation there.
# The goal of the first two transformations is to get from the
# data space (in this case longitude and latitude) to Axes
# space. It is separated into a non-affine and affine part so
# that the non-affine part does not have to be recomputed when
# a simple affine change to the figure has been made (such as
# resizing the window or changing the dpi).
# 1) The core transformation from data space into
# rectilinear space defined in the HammerTransform class.
self.transProjection = self._get_core_transform(self.RESOLUTION)
# 2) The above has an output range that is not in the unit
# rectangle, so scale and translate it so it fits correctly
# within the Axes. The peculiar calculations of xscale and
# yscale are specific to an Aitoff-Hammer projection, so don't
# worry about them too much.
self.transAffine = self._get_affine_transform()
# 3) This is the transformation from Axes space to display
# space.
self.transAxes = BboxTransformTo(self.bbox)
# Now put these 3 transforms together -- from data all the way
# to display coordinates. Using the '+' operator, these
# transforms will be applied "in order". The transforms are
# automatically simplified, if possible, by the underlying
# transformation framework.
self.transData = \
self.transProjection + \
self.transAffine + \
self.transAxes
# The main data transformation is set up. Now deal with
# gridlines and tick labels.
# Longitude gridlines and ticklabels. The input to these
# transforms are in display space in x and Axes space in y.
# Therefore, the input values will be in range (-xmin, 0),
# (xmax, 1). The goal of these transforms is to go from that
# space to display space. The tick labels will be offset 4
# pixels from the equator.
self._xaxis_pretransform = \
Affine2D() \
.scale(1.0, self._longitude_cap * 2.0) \
.translate(0.0, -self._longitude_cap)
self._xaxis_transform = \
self._xaxis_pretransform + \
self.transData
self._xaxis_text1_transform = \
Affine2D().scale(1.0, 0.0) + \
self.transData + \
Affine2D().translate(0.0, 4.0)
self._xaxis_text2_transform = \
Affine2D().scale(1.0, 0.0) + \
self.transData + \
Affine2D().translate(0.0, -4.0)
# Now set up the transforms for the latitude ticks. The input to
# these transforms are in Axes space in x and display space in
# y. Therefore, the input values will be in range (0, -ymin),
# (1, ymax). The goal of these transforms is to go from that
# space to display space. The tick labels will be offset 4
# pixels from the edge of the Axes ellipse.
yaxis_stretch = Affine2D().scale(np.pi*2, 1).translate(-np.pi, 0)
yaxis_space = Affine2D().scale(1.0, 1.1)
self._yaxis_transform = \
yaxis_stretch + \
self.transData
yaxis_text_base = \
yaxis_stretch + \
self.transProjection + \
(yaxis_space +
self.transAffine +
self.transAxes)
self._yaxis_text1_transform = \
yaxis_text_base + \
Affine2D().translate(-8.0, 0.0)
self._yaxis_text2_transform = \
yaxis_text_base + \
Affine2D().translate(8.0, 0.0)
def _get_affine_transform(self):
transform = self._get_core_transform(1)
xscale, _ = transform.transform((np.pi, 0))
_, yscale = transform.transform((0, np.pi/2))
return Affine2D() \
.scale(0.5 / xscale, 0.5 / yscale) \
.translate(0.5, 0.5)
def get_xaxis_transform(self, which='grid'):
"""
Override this method to provide a transformation for the
x-axis tick labels.
Returns a tuple of the form (transform, valign, halign)
"""
if which not in ['tick1', 'tick2', 'grid']:
raise ValueError(
"'which' must be one of 'tick1', 'tick2', or 'grid'")
return self._xaxis_transform
def get_xaxis_text1_transform(self, pad):
return self._xaxis_text1_transform, 'bottom', 'center'
def get_xaxis_text2_transform(self, pad):
"""
Override this method to provide a transformation for the
secondary x-axis tick labels.
Returns a tuple of the form (transform, valign, halign)
"""
return self._xaxis_text2_transform, 'top', 'center'
def get_yaxis_transform(self, which='grid'):
"""
Override this method to provide a transformation for the
y-axis grid and ticks.
"""
if which not in ['tick1', 'tick2', 'grid']:
raise ValueError(
"'which' must be one of 'tick1', 'tick2', or 'grid'")
return self._yaxis_transform
def get_yaxis_text1_transform(self, pad):
"""
Override this method to provide a transformation for the
y-axis tick labels.
Returns a tuple of the form (transform, valign, halign)
"""
return self._yaxis_text1_transform, 'center', 'right'
def get_yaxis_text2_transform(self, pad):
"""
Override this method to provide a transformation for the
secondary y-axis tick labels.
Returns a tuple of the form (transform, valign, halign)
"""
return self._yaxis_text2_transform, 'center', 'left'
def _gen_axes_patch(self):
"""
Override this method to define the shape that is used for the
background of the plot. It should be a subclass of Patch.
In this case, it is a Circle (that may be warped by the Axes
transform into an ellipse). Any data and gridlines will be
clipped to this shape.
"""
return Circle((0.5, 0.5), 0.5)
def _gen_axes_spines(self):
return {'geo': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)}
def set_yscale(self, *args, **kwargs):
if args[0] != 'linear':
raise NotImplementedError
# Prevent the user from applying scales to one or both of the
# axes. In this particular case, scaling the axes wouldn't make
# sense, so we don't allow it.
set_xscale = set_yscale
# Prevent the user from changing the axes limits. In our case, we
# want to display the whole sphere all the time, so we override
# set_xlim and set_ylim to ignore any input. This also applies to
# interactive panning and zooming in the GUI interfaces.
def set_xlim(self, *args, **kwargs):
raise TypeError("Changing axes limits of a geographic projection is "
"not supported. Please consider using Cartopy.")
set_ylim = set_xlim
def format_coord(self, lon, lat):
"""
Override this method to change how the values are displayed in
the status bar.
In this case, we want them to be displayed in degrees N/S/E/W.
"""
lon, lat = np.rad2deg([lon, lat])
ns = 'N' if lat >= 0.0 else 'S'
ew = 'E' if lon >= 0.0 else 'W'
return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s'
% (abs(lat), ns, abs(lon), ew))
def set_longitude_grid(self, degrees):
"""
Set the number of degrees between each longitude grid.
This is an example method that is specific to this projection
class -- it provides a more convenient interface to set the
ticking than set_xticks would.
"""
# Skip -180 and 180, which are the fixed limits.
grid = np.arange(-180 + degrees, 180, degrees)
self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))
self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))
def set_latitude_grid(self, degrees):
"""
Set the number of degrees between each longitude grid.
This is an example method that is specific to this projection
class -- it provides a more convenient interface than
set_yticks would.
"""
# Skip -90 and 90, which are the fixed limits.
grid = np.arange(-90 + degrees, 90, degrees)
self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))
self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))
def set_longitude_grid_ends(self, degrees):
"""
Set the latitude(s) at which to stop drawing the longitude grids.
Often, in geographic projections, you wouldn't want to draw
longitude gridlines near the poles. This allows the user to
specify the degree at which to stop drawing longitude grids.
This is an example method that is specific to this projection
class -- it provides an interface to something that has no
analogy in the base Axes class.
"""
self._longitude_cap = np.deg2rad(degrees)
self._xaxis_pretransform \
.clear() \
.scale(1.0, self._longitude_cap * 2.0) \
.translate(0.0, -self._longitude_cap)
def get_data_ratio(self):
"""
Return the aspect ratio of the data itself.
This method should be overridden by any Axes that have a
fixed data ratio.
"""
return 1.0
# Interactive panning and zooming is not supported with this projection,
# so we override all of the following methods to disable it.
def can_zoom(self):
"""
Return whether this Axes supports the zoom box button functionality.
This Axes object does not support interactive zoom box.
"""
return False
def can_pan(self):
"""
Return whether this Axes supports the pan/zoom button functionality.
This Axes object does not support interactive pan/zoom.
"""
return False
def start_pan(self, x, y, button):
pass
def end_pan(self):
pass
def drag_pan(self, button, key, x, y):
pass
class HammerAxes(GeoAxes):
"""
A custom class for the Aitoff-Hammer projection, an equal-area map
projection.
https://en.wikipedia.org/wiki/Hammer_projection
"""
# The projection must specify a name. This will be used by the
# user to select the projection,
# i.e. ``subplot(projection='custom_hammer')``.
name = 'custom_hammer'
class HammerTransform(Transform):
"""The base Hammer transform."""
input_dims = output_dims = 2
def __init__(self, resolution):
"""
Create a new Hammer transform. Resolution is the number of steps
to interpolate between each input line segment to approximate its
path in curved Hammer space.
"""
Transform.__init__(self)
self._resolution = resolution
def transform_non_affine(self, ll):
longitude, latitude = ll.T
# Pre-compute some values
half_long = longitude / 2
cos_latitude = np.cos(latitude)
sqrt2 = np.sqrt(2)
alpha = np.sqrt(1 + cos_latitude * np.cos(half_long))
x = (2 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha
y = (sqrt2 * np.sin(latitude)) / alpha
return np.column_stack([x, y])
def transform_path_non_affine(self, path):
# vertices = path.vertices
ipath = path.interpolated(self._resolution)
return Path(self.transform(ipath.vertices), ipath.codes)
def inverted(self):
return HammerAxes.InvertedHammerTransform(self._resolution)
class InvertedHammerTransform(Transform):
input_dims = output_dims = 2
def __init__(self, resolution):
Transform.__init__(self)
self._resolution = resolution
def transform_non_affine(self, xy):
x, y = xy.T
z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2)
longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1)))
latitude = np.arcsin(y*z)
return np.column_stack([longitude, latitude])
def inverted(self):
return HammerAxes.HammerTransform(self._resolution)
def __init__(self, *args, **kwargs):
self._longitude_cap = np.pi / 2.0
super().__init__(*args, **kwargs)
self.set_aspect(0.5, adjustable='box', anchor='C')
self.clear()
def _get_core_transform(self, resolution):
return self.HammerTransform(resolution)
# Now register the projection with Matplotlib so the user can select it.
register_projection(HammerAxes)
if __name__ == '__main__':
import matplotlib.pyplot as plt
# Now make a simple example using the custom projection.
fig, ax = plt.subplots(subplot_kw={'projection': 'custom_hammer'})
ax.plot([-1, 1, 1], [-1, -1, 1], "o-")
ax.grid()
plt.show()
| stable__gallery__misc__custom_projection | 0 | figure_000.png | Custom projection — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/custom_projection.html#sphx-glr-download-gallery-misc-custom-projection-py | https://matplotlib.org/stable/_downloads/2de7d801cc807aadc92f195e3402760b/custom_projection.py | custom_projection.py | misc | ok | 1 | null | |
"""
============
Customize Rc
============
I'm not trying to make a good-looking figure here, but just to show
some examples of customizing `.rcParams` on the fly.
If you like to work interactively, and need to create different sets
of defaults for figures (e.g., one set of defaults for publication, one
set for interactive exploration), you may want to define some
functions in a custom module that set the defaults, e.g.,::
def set_pub():
rcParams.update({
"font.weight": "bold", # bold fonts
"tick.labelsize": 15, # large tick labels
"lines.linewidth": 1, # thick lines
"lines.color": "k", # black lines
"grid.color": "0.5", # gray gridlines
"grid.linestyle": "-", # solid gridlines
"grid.linewidth": 0.5, # thin gridlines
"savefig.dpi": 300, # higher resolution output.
})
Then as you are working interactively, you just need to do::
>>> set_pub()
>>> plot([1, 2, 3])
>>> savefig('myfig')
>>> rcdefaults() # restore the defaults
"""
import matplotlib.pyplot as plt
plt.subplot(311)
plt.plot([1, 2, 3])
# the axes attributes need to be set before the call to subplot
plt.rcParams.update({
"font.weight": "bold",
"xtick.major.size": 5,
"xtick.major.pad": 7,
"xtick.labelsize": 15,
"grid.color": "0.5",
"grid.linestyle": "-",
"grid.linewidth": 5,
"lines.linewidth": 2,
"lines.color": "g",
})
plt.subplot(312)
plt.plot([1, 2, 3])
plt.grid(True)
plt.rcdefaults()
plt.subplot(313)
plt.plot([1, 2, 3])
plt.grid(True)
plt.show()
| stable__gallery__misc__customize_rc | 0 | figure_000.png | Customize Rc — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/customize_rc.html#sphx-glr-download-gallery-misc-customize-rc-py | https://matplotlib.org/stable/_downloads/d10d0de4c4efa82daca1fa3f98c048cd/customize_rc.py | customize_rc.py | misc | ok | 1 | null | |
"""
==========
AGG filter
==========
Most pixel-based backends in Matplotlib use `Anti-Grain Geometry (AGG)`_ for
rendering. You can modify the rendering of Artists by applying a filter via
`.Artist.set_agg_filter`.
.. _Anti-Grain Geometry (AGG): http://agg.sourceforge.net/antigrain.com
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.artist import Artist
import matplotlib.cm as cm
from matplotlib.colors import LightSource
import matplotlib.transforms as mtransforms
def smooth1d(x, window_len):
# copied from https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html
s = np.r_[2*x[0] - x[window_len:1:-1], x, 2*x[-1] - x[-1:-window_len:-1]]
w = np.hanning(window_len)
y = np.convolve(w/w.sum(), s, mode='same')
return y[window_len-1:-window_len+1]
def smooth2d(A, sigma=3):
window_len = max(int(sigma), 3) * 2 + 1
A = np.apply_along_axis(smooth1d, 0, A, window_len)
A = np.apply_along_axis(smooth1d, 1, A, window_len)
return A
class BaseFilter:
def get_pad(self, dpi):
return 0
def process_image(self, padded_src, dpi):
raise NotImplementedError("Should be overridden by subclasses")
def __call__(self, im, dpi):
pad = self.get_pad(dpi)
padded_src = np.pad(im, [(pad, pad), (pad, pad), (0, 0)], "constant")
tgt_image = self.process_image(padded_src, dpi)
return tgt_image, -pad, -pad
class OffsetFilter(BaseFilter):
def __init__(self, offsets=(0, 0)):
self.offsets = offsets
def get_pad(self, dpi):
return int(max(self.offsets) / 72 * dpi)
def process_image(self, padded_src, dpi):
ox, oy = self.offsets
a1 = np.roll(padded_src, int(ox / 72 * dpi), axis=1)
a2 = np.roll(a1, -int(oy / 72 * dpi), axis=0)
return a2
class GaussianFilter(BaseFilter):
"""Simple Gaussian filter."""
def __init__(self, sigma, alpha=0.5, color=(0, 0, 0)):
self.sigma = sigma
self.alpha = alpha
self.color = color
def get_pad(self, dpi):
return int(self.sigma*3 / 72 * dpi)
def process_image(self, padded_src, dpi):
tgt_image = np.empty_like(padded_src)
tgt_image[:, :, :3] = self.color
tgt_image[:, :, 3] = smooth2d(padded_src[:, :, 3] * self.alpha,
self.sigma / 72 * dpi)
return tgt_image
class DropShadowFilter(BaseFilter):
def __init__(self, sigma, alpha=0.3, color=(0, 0, 0), offsets=(0, 0)):
self.gauss_filter = GaussianFilter(sigma, alpha, color)
self.offset_filter = OffsetFilter(offsets)
def get_pad(self, dpi):
return max(self.gauss_filter.get_pad(dpi),
self.offset_filter.get_pad(dpi))
def process_image(self, padded_src, dpi):
t1 = self.gauss_filter.process_image(padded_src, dpi)
t2 = self.offset_filter.process_image(t1, dpi)
return t2
class LightFilter(BaseFilter):
"""Apply LightSource filter"""
def __init__(self, sigma, fraction=1):
"""
Parameters
----------
sigma : float
sigma for gaussian filter
fraction: number, default: 1
Increases or decreases the contrast of the hillshade.
See `matplotlib.colors.LightSource`
"""
self.gauss_filter = GaussianFilter(sigma, alpha=1)
self.light_source = LightSource()
self.fraction = fraction
def get_pad(self, dpi):
return self.gauss_filter.get_pad(dpi)
def process_image(self, padded_src, dpi):
t1 = self.gauss_filter.process_image(padded_src, dpi)
elevation = t1[:, :, 3]
rgb = padded_src[:, :, :3]
alpha = padded_src[:, :, 3:]
rgb2 = self.light_source.shade_rgb(rgb, elevation,
fraction=self.fraction,
blend_mode="overlay")
return np.concatenate([rgb2, alpha], -1)
class GrowFilter(BaseFilter):
"""Enlarge the area."""
def __init__(self, pixels, color=(1, 1, 1)):
self.pixels = pixels
self.color = color
def __call__(self, im, dpi):
alpha = np.pad(im[..., 3], self.pixels, "constant")
alpha2 = np.clip(smooth2d(alpha, self.pixels / 72 * dpi) * 5, 0, 1)
new_im = np.empty((*alpha2.shape, 4))
new_im[:, :, :3] = self.color
new_im[:, :, 3] = alpha2
offsetx, offsety = -self.pixels, -self.pixels
return new_im, offsetx, offsety
class FilteredArtistList(Artist):
"""A simple container to filter multiple artists at once."""
def __init__(self, artist_list, filter):
super().__init__()
self._artist_list = artist_list
self._filter = filter
def draw(self, renderer):
renderer.start_rasterizing()
renderer.start_filter()
for a in self._artist_list:
a.draw(renderer)
renderer.stop_filter(self._filter)
renderer.stop_rasterizing()
def filtered_text(ax):
# mostly copied from contour_demo.py
# prepare image
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
# draw
ax.imshow(Z, interpolation='bilinear', origin='lower',
cmap=cm.gray, extent=(-3, 3, -2, 2), aspect='auto')
levels = np.arange(-1.2, 1.6, 0.2)
CS = ax.contour(Z, levels,
origin='lower',
linewidths=2,
extent=(-3, 3, -2, 2))
# contour label
cl = ax.clabel(CS, levels[1::2], # label every second level
fmt='%1.1f',
fontsize=11)
# change clabel color to black
from matplotlib.patheffects import Normal
for t in cl:
t.set_color("k")
# to force TextPath (i.e., same font in all backends)
t.set_path_effects([Normal()])
# Add white glows to improve visibility of labels.
white_glows = FilteredArtistList(cl, GrowFilter(3))
ax.add_artist(white_glows)
white_glows.set_zorder(cl[0].get_zorder() - 0.1)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def drop_shadow_line(ax):
# copied from examples/misc/svg_filter_line.py
# draw lines
l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-")
l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-")
gauss = DropShadowFilter(4)
for l in [l1, l2]:
# draw shadows with same lines with slight offset.
xx = l.get_xdata()
yy = l.get_ydata()
shadow, = ax.plot(xx, yy)
shadow.update_from(l)
# offset transform
transform = mtransforms.offset_copy(l.get_transform(), ax.figure,
x=4.0, y=-6.0, units='points')
shadow.set_transform(transform)
# adjust zorder of the shadow lines so that it is drawn below the
# original lines
shadow.set_zorder(l.get_zorder() - 0.5)
shadow.set_agg_filter(gauss)
shadow.set_rasterized(True) # to support mixed-mode renderers
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def drop_shadow_patches(ax):
# Copied from barchart_demo.py
N = 5
group1_means = [20, 35, 30, 35, 27]
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
rects1 = ax.bar(ind, group1_means, width, color='r', ec="w", lw=2)
group2_means = [25, 32, 34, 20, 25]
rects2 = ax.bar(ind + width + 0.1, group2_means, width,
color='y', ec="w", lw=2)
drop = DropShadowFilter(5, offsets=(1, 1))
shadow = FilteredArtistList(rects1 + rects2, drop)
ax.add_artist(shadow)
shadow.set_zorder(rects1[0].get_zorder() - 0.1)
ax.set_ylim(0, 40)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def light_filter_pie(ax):
fracs = [15, 30, 45, 10]
explode = (0.1, 0.2, 0.1, 0.1)
pies = ax.pie(fracs, explode=explode)
light_filter = LightFilter(9)
for p in pies[0]:
p.set_agg_filter(light_filter)
p.set_rasterized(True) # to support mixed-mode renderers
p.set(ec="none",
lw=2)
gauss = DropShadowFilter(9, offsets=(3, -4), alpha=0.7)
shadow = FilteredArtistList(pies[0], gauss)
ax.add_artist(shadow)
shadow.set_zorder(pies[0][0].get_zorder() - 0.1)
if __name__ == "__main__":
fix, axs = plt.subplots(2, 2)
filtered_text(axs[0, 0])
drop_shadow_line(axs[0, 1])
drop_shadow_patches(axs[1, 0])
light_filter_pie(axs[1, 1])
axs[1, 1].set_frame_on(True)
plt.show()
| stable__gallery__misc__demo_agg_filter | 0 | figure_000.png | AGG filter — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/demo_agg_filter.html#sphx-glr-download-gallery-misc-demo-agg-filter-py | https://matplotlib.org/stable/_downloads/5787bdd3c2fb5d84c40860c89508a642/demo_agg_filter.py | demo_agg_filter.py | misc | ok | 1 | null | |
"""
==========
Ribbon box
==========
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook
from matplotlib import colors as mcolors
from matplotlib.image import AxesImage
from matplotlib.transforms import Bbox, BboxTransformTo, TransformedBbox
class RibbonBox:
original_image = plt.imread(
cbook.get_sample_data("Minduka_Present_Blue_Pack.png"))
cut_location = 70
b_and_h = original_image[:, :, 2:3]
color = original_image[:, :, 2:3] - original_image[:, :, 0:1]
alpha = original_image[:, :, 3:4]
nx = original_image.shape[1]
def __init__(self, color):
rgb = mcolors.to_rgb(color)
self.im = np.dstack(
[self.b_and_h - self.color * (1 - np.array(rgb)), self.alpha])
def get_stretched_image(self, stretch_factor):
stretch_factor = max(stretch_factor, 1)
ny, nx, nch = self.im.shape
ny2 = int(ny*stretch_factor)
return np.vstack(
[self.im[:self.cut_location],
np.broadcast_to(
self.im[self.cut_location], (ny2 - ny, nx, nch)),
self.im[self.cut_location:]])
class RibbonBoxImage(AxesImage):
zorder = 1
def __init__(self, ax, bbox, color, *, extent=(0, 1, 0, 1), **kwargs):
super().__init__(ax, extent=extent, **kwargs)
self._bbox = bbox
self._ribbonbox = RibbonBox(color)
self.set_transform(BboxTransformTo(bbox))
def draw(self, renderer):
stretch_factor = self._bbox.height / self._bbox.width
ny = int(stretch_factor*self._ribbonbox.nx)
if self.get_array() is None or self.get_array().shape[0] != ny:
arr = self._ribbonbox.get_stretched_image(stretch_factor)
self.set_array(arr)
super().draw(renderer)
def main():
fig, ax = plt.subplots()
years = np.arange(2004, 2009)
heights = [7900, 8100, 7900, 6900, 2800]
box_colors = [
(0.8, 0.2, 0.2),
(0.2, 0.8, 0.2),
(0.2, 0.2, 0.8),
(0.7, 0.5, 0.8),
(0.3, 0.8, 0.7),
]
for year, h, bc in zip(years, heights, box_colors):
bbox0 = Bbox.from_extents(year - 0.4, 0., year + 0.4, h)
bbox = TransformedBbox(bbox0, ax.transData)
ax.add_artist(RibbonBoxImage(ax, bbox, bc, interpolation="bicubic"))
ax.annotate(str(h), (year, h), va="bottom", ha="center")
ax.set_xlim(years[0] - 0.5, years[-1] + 0.5)
ax.set_ylim(0, 10000)
background_gradient = np.zeros((2, 2, 4))
background_gradient[:, :, :3] = [1, 1, 0]
background_gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]] # alpha channel
ax.imshow(background_gradient, interpolation="bicubic", zorder=0.1,
extent=(0, 1, 0, 1), transform=ax.transAxes)
plt.show()
main()
| stable__gallery__misc__demo_ribbon_box | 0 | figure_000.png | Ribbon box — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/demo_ribbon_box.html#sphx-glr-download-gallery-misc-demo-ribbon-box-py | https://matplotlib.org/stable/_downloads/c7b27332a2e53923edb7ffb5315d4fa3/demo_ribbon_box.py | demo_ribbon_box.py | misc | ok | 1 | null | |
"""
==============================
Add lines directly to a figure
==============================
You can add artists such as a `.Line2D` directly to a figure. This is
typically useful for visual structuring.
.. redirect-from:: /gallery/pyplots/fig_x
"""
import matplotlib.pyplot as plt
import matplotlib.lines as lines
fig, axs = plt.subplots(2, 2, gridspec_kw={'hspace': 0.4, 'wspace': 0.4})
fig.add_artist(lines.Line2D([0, 1], [0.47, 0.47], linewidth=3))
fig.add_artist(lines.Line2D([0.5, 0.5], [1, 0], linewidth=3))
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.pyplot.figure`
# - `matplotlib.lines`
# - `matplotlib.lines.Line2D`
| stable__gallery__misc__fig_x | 0 | figure_000.png | Add lines directly to a figure — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/fig_x.html#sphx-glr-download-gallery-misc-fig-x-py | https://matplotlib.org/stable/_downloads/9081f921ee64a1df1186094d7dd9a8d3/fig_x.py | fig_x.py | misc | ok | 1 | null | |
"""
===========
Fill spiral
===========
"""
import matplotlib.pyplot as plt
import numpy as np
theta = np.arange(0, 8*np.pi, 0.1)
a = 1
b = .2
for dt in np.arange(0, 2*np.pi, np.pi/2.0):
x = a*np.cos(theta + dt)*np.exp(b*theta)
y = a*np.sin(theta + dt)*np.exp(b*theta)
dt = dt + np.pi/4.0
x2 = a*np.cos(theta + dt)*np.exp(b*theta)
y2 = a*np.sin(theta + dt)*np.exp(b*theta)
xf = np.concatenate((x, x2[::-1]))
yf = np.concatenate((y, y2[::-1]))
p1 = plt.fill(xf, yf)
plt.show()
| stable__gallery__misc__fill_spiral | 0 | figure_000.png | Fill spiral — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/fill_spiral.html#sphx-glr-download-gallery-misc-fill-spiral-py | https://matplotlib.org/stable/_downloads/61f5d448be497db6a30387b809ee77d1/fill_spiral.py | fill_spiral.py | misc | ok | 1 | null | |
"""
============
Findobj Demo
============
Recursively find all objects that match some criteria
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.text as text
a = np.arange(0, 3, .02)
b = np.arange(0, 3, .02)
c = np.exp(a)
d = c[::-1]
fig, ax = plt.subplots()
plt.plot(a, c, 'k--', a, d, 'k:', a, c + d, 'k')
plt.legend(('Model length', 'Data length', 'Total message length'),
loc='upper center', shadow=True)
plt.ylim([-1, 20])
plt.grid(False)
plt.xlabel('Model complexity --->')
plt.ylabel('Message length --->')
plt.title('Minimum Message Length')
# match on arbitrary function
def myfunc(x):
return hasattr(x, 'set_color') and not hasattr(x, 'set_facecolor')
for o in fig.findobj(myfunc):
o.set_color('blue')
# match on class instances
for o in fig.findobj(text.Text):
o.set_fontstyle('italic')
plt.show()
| stable__gallery__misc__findobj_demo | 0 | figure_000.png | Findobj Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/findobj_demo.html#sphx-glr-download-gallery-misc-findobj-demo-py | https://matplotlib.org/stable/_downloads/4095e40bfdaeea40b5ebf921dca65a60/findobj_demo.py | findobj_demo.py | misc | ok | 1 | null | |
"""
========================================================
Building histograms using Rectangles and PolyCollections
========================================================
Using a path patch to draw rectangles.
The technique of using lots of `.Rectangle` instances, or the faster method of
using `.PolyCollection`, were implemented before we had proper paths with
moveto, lineto, closepoly, etc. in Matplotlib. Now that we have them, we can
draw collections of regularly shaped objects with homogeneous properties more
efficiently with a PathCollection. This example makes a histogram -- it's more
work to set up the vertex arrays at the outset, but it should be much faster
for large numbers of objects.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as patches
import matplotlib.path as path
np.random.seed(19680801) # Fixing random state for reproducibility
# histogram our data with numpy
data = np.random.randn(1000)
n, bins = np.histogram(data, 50)
# get the corners of the rectangles for the histogram
left = bins[:-1]
right = bins[1:]
bottom = np.zeros(len(left))
top = bottom + n
# we need a (numrects x numsides x 2) numpy array for the path helper
# function to build a compound path
XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T
# get the Path object
barpath = path.Path.make_compound_path_from_polys(XY)
# make a patch out of it, don't add a margin at y=0
patch = patches.PathPatch(barpath)
patch.sticky_edges.y[:] = [0]
fig, ax = plt.subplots()
ax.add_patch(patch)
ax.autoscale_view()
plt.show()
# %%
# Instead of creating a three-dimensional array and using
# `~.path.Path.make_compound_path_from_polys`, we could as well create the
# compound path directly using vertices and codes as shown below
nrects = len(left)
nverts = nrects*(1+3+1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
barpath = path.Path(verts, codes)
# make a patch out of it, don't add a margin at y=0
patch = patches.PathPatch(barpath)
patch.sticky_edges.y[:] = [0]
fig, ax = plt.subplots()
ax.add_patch(patch)
ax.autoscale_view()
plt.show()
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.patches`
# - `matplotlib.patches.PathPatch`
# - `matplotlib.path`
# - `matplotlib.path.Path`
# - `matplotlib.path.Path.make_compound_path_from_polys`
# - `matplotlib.axes.Axes.add_patch`
# - `matplotlib.collections.PathCollection`
#
# This example shows an alternative to
#
# - `matplotlib.collections.PolyCollection`
# - `matplotlib.axes.Axes.hist`
| stable__gallery__misc__histogram_path | 0 | figure_000.png | Building histograms using Rectangles and PolyCollections — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/histogram_path.html#sphx-glr-download-gallery-misc-histogram-path-py | https://matplotlib.org/stable/_downloads/5397c6ff8f61d4375f2fa83fa0eaf135/histogram_path.py | histogram_path.py | misc | ok | 2 | null | |
"""
==========
Hyperlinks
==========
This example demonstrates how to set a hyperlinks on various kinds of elements.
This currently only works with the SVG backend.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
# %%
fig = plt.figure()
s = plt.scatter([1, 2, 3], [4, 5, 6])
s.set_urls(['https://www.bbc.com/news', 'https://www.google.com/', None])
fig.savefig('scatter.svg')
# %%
fig = plt.figure()
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray,
origin='lower', extent=(-3, 3, -3, 3))
im.set_url('https://www.google.com/')
fig.savefig('image.svg')
| stable__gallery__misc__hyperlinks_sgskip | 0 | figure_000.png | Hyperlinks — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/hyperlinks_sgskip.html#sphx-glr-download-gallery-misc-hyperlinks-sgskip-py | https://matplotlib.org/stable/_downloads/00c94fd2ec27d6cef4b040acefbf730d/hyperlinks_sgskip.py | hyperlinks_sgskip.py | misc | ok | 2 | null | |
"""
==========
Hyperlinks
==========
This example demonstrates how to set a hyperlinks on various kinds of elements.
This currently only works with the SVG backend.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
# %%
fig = plt.figure()
s = plt.scatter([1, 2, 3], [4, 5, 6])
s.set_urls(['https://www.bbc.com/news', 'https://www.google.com/', None])
fig.savefig('scatter.svg')
# %%
fig = plt.figure()
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray,
origin='lower', extent=(-3, 3, -3, 3))
im.set_url('https://www.google.com/')
fig.savefig('image.svg')
| stable__gallery__misc__hyperlinks_sgskip | 1 | figure_001.png | Hyperlinks — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/hyperlinks_sgskip.html#sphx-glr-download-gallery-misc-hyperlinks-sgskip-py | https://matplotlib.org/stable/_downloads/00c94fd2ec27d6cef4b040acefbf730d/hyperlinks_sgskip.py | hyperlinks_sgskip.py | misc | ok | 2 | null | |
"""
======================
Plotting with keywords
======================
Some data structures, like dict, `structured numpy array
<https://numpy.org/doc/stable/user/basics.rec.html#structured-arrays>`_
or `pandas.DataFrame` provide access to labelled data via string index access
``data[key]``.
For these data types, Matplotlib supports passing the whole datastructure via the
``data`` keyword argument, and using the string names as plot function parameters,
where you'd normally pass in your data.
"""
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
fig, ax = plt.subplots()
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set(xlabel='entry a', ylabel='entry b')
plt.show()
| stable__gallery__misc__keyword_plotting | 0 | figure_000.png | Plotting with keywords — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/keyword_plotting.html#sphx-glr-download-gallery-misc-keyword-plotting-py | https://matplotlib.org/stable/_downloads/0c0bceec5b66dc4841d06be6852509dc/keyword_plotting.py | keyword_plotting.py | misc | ok | 1 | null | |
"""
===============
Matplotlib logo
===============
This example generates the current matplotlib logo.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.font_manager
from matplotlib.patches import PathPatch, Rectangle
from matplotlib.text import TextPath
import matplotlib.transforms as mtrans
MPL_BLUE = '#11557c'
def get_font_properties():
# The original font is Calibri, if that is not installed, we fall back
# to Carlito, which is metrically equivalent.
if 'Calibri' in matplotlib.font_manager.findfont('Calibri:bold'):
return matplotlib.font_manager.FontProperties(family='Calibri',
weight='bold')
if 'Carlito' in matplotlib.font_manager.findfont('Carlito:bold'):
print('Original font not found. Falling back to Carlito. '
'The logo text will not be in the correct font.')
return matplotlib.font_manager.FontProperties(family='Carlito',
weight='bold')
print('Original font not found. '
'The logo text will not be in the correct font.')
return None
def create_icon_axes(fig, ax_position, lw_bars, lw_grid, lw_border, rgrid):
"""
Create a polar Axes containing the matplotlib radar plot.
Parameters
----------
fig : matplotlib.figure.Figure
The figure to draw into.
ax_position : (float, float, float, float)
The position of the created Axes in figure coordinates as
(x, y, width, height).
lw_bars : float
The linewidth of the bars.
lw_grid : float
The linewidth of the grid.
lw_border : float
The linewidth of the Axes border.
rgrid : array-like
Positions of the radial grid.
Returns
-------
ax : matplotlib.axes.Axes
The created Axes.
"""
with plt.rc_context({'axes.edgecolor': MPL_BLUE,
'axes.linewidth': lw_border}):
ax = fig.add_axes(ax_position, projection='polar')
ax.set_axisbelow(True)
N = 7
arc = 2. * np.pi
theta = np.arange(0.0, arc, arc / N)
radii = np.array([2, 6, 8, 7, 4, 5, 8])
width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3])
bars = ax.bar(theta, radii, width=width, bottom=0.0, align='edge',
edgecolor='0.3', lw=lw_bars)
for r, bar in zip(radii, bars):
color = *cm.jet(r / 10.)[:3], 0.6 # color from jet with alpha=0.6
bar.set_facecolor(color)
ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
ax.grid(lw=lw_grid, color='0.9')
ax.set_rmax(9)
ax.set_yticks(rgrid)
# the actual visible background - extends a bit beyond the axis
ax.add_patch(Rectangle((0, 0), arc, 9.58,
facecolor='white', zorder=0,
clip_on=False, in_layout=False))
return ax
def create_text_axes(fig, height_px):
"""Create an Axes in *fig* that contains 'matplotlib' as Text."""
ax = fig.add_axes((0, 0, 1, 1))
ax.set_aspect("equal")
ax.set_axis_off()
path = TextPath((0, 0), "matplotlib", size=height_px * 0.8,
prop=get_font_properties())
angle = 4.25 # degrees
trans = mtrans.Affine2D().skew_deg(angle, 0)
patch = PathPatch(path, transform=trans + ax.transData, color=MPL_BLUE,
lw=0)
ax.add_patch(patch)
ax.autoscale()
def make_logo(height_px, lw_bars, lw_grid, lw_border, rgrid, with_text=False):
"""
Create a full figure with the Matplotlib logo.
Parameters
----------
height_px : int
Height of the figure in pixel.
lw_bars : float
The linewidth of the bar border.
lw_grid : float
The linewidth of the grid.
lw_border : float
The linewidth of icon border.
rgrid : sequence of float
The radial grid positions.
with_text : bool
Whether to draw only the icon or to include 'matplotlib' as text.
"""
dpi = 100
height = height_px / dpi
figsize = (5 * height, height) if with_text else (height, height)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
if with_text:
create_text_axes(fig, height_px)
ax_pos = (0.535, 0.12, .17, 0.75) if with_text else (0.03, 0.03, .94, .94)
ax = create_icon_axes(fig, ax_pos, lw_bars, lw_grid, lw_border, rgrid)
return fig, ax
# %%
# A large logo:
make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1,
rgrid=[1, 3, 5, 7])
# %%
# A small 32px logo:
make_logo(height_px=32, lw_bars=0.3, lw_grid=0.3, lw_border=0.3, rgrid=[5])
# %%
# A large logo including text, as used on the matplotlib website.
make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1,
rgrid=[1, 3, 5, 7], with_text=True)
plt.show()
| stable__gallery__misc__logos2 | 0 | figure_000.png | Matplotlib logo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/logos2.html#sphx-glr-download-gallery-misc-logos2-py | https://matplotlib.org/stable/_downloads/0846c3e5d114c457e124451aea9e558a/logos2.py | logos2.py | misc | ok | 3 | null | |
"""
===============
Matplotlib logo
===============
This example generates the current matplotlib logo.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.font_manager
from matplotlib.patches import PathPatch, Rectangle
from matplotlib.text import TextPath
import matplotlib.transforms as mtrans
MPL_BLUE = '#11557c'
def get_font_properties():
# The original font is Calibri, if that is not installed, we fall back
# to Carlito, which is metrically equivalent.
if 'Calibri' in matplotlib.font_manager.findfont('Calibri:bold'):
return matplotlib.font_manager.FontProperties(family='Calibri',
weight='bold')
if 'Carlito' in matplotlib.font_manager.findfont('Carlito:bold'):
print('Original font not found. Falling back to Carlito. '
'The logo text will not be in the correct font.')
return matplotlib.font_manager.FontProperties(family='Carlito',
weight='bold')
print('Original font not found. '
'The logo text will not be in the correct font.')
return None
def create_icon_axes(fig, ax_position, lw_bars, lw_grid, lw_border, rgrid):
"""
Create a polar Axes containing the matplotlib radar plot.
Parameters
----------
fig : matplotlib.figure.Figure
The figure to draw into.
ax_position : (float, float, float, float)
The position of the created Axes in figure coordinates as
(x, y, width, height).
lw_bars : float
The linewidth of the bars.
lw_grid : float
The linewidth of the grid.
lw_border : float
The linewidth of the Axes border.
rgrid : array-like
Positions of the radial grid.
Returns
-------
ax : matplotlib.axes.Axes
The created Axes.
"""
with plt.rc_context({'axes.edgecolor': MPL_BLUE,
'axes.linewidth': lw_border}):
ax = fig.add_axes(ax_position, projection='polar')
ax.set_axisbelow(True)
N = 7
arc = 2. * np.pi
theta = np.arange(0.0, arc, arc / N)
radii = np.array([2, 6, 8, 7, 4, 5, 8])
width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3])
bars = ax.bar(theta, radii, width=width, bottom=0.0, align='edge',
edgecolor='0.3', lw=lw_bars)
for r, bar in zip(radii, bars):
color = *cm.jet(r / 10.)[:3], 0.6 # color from jet with alpha=0.6
bar.set_facecolor(color)
ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
ax.grid(lw=lw_grid, color='0.9')
ax.set_rmax(9)
ax.set_yticks(rgrid)
# the actual visible background - extends a bit beyond the axis
ax.add_patch(Rectangle((0, 0), arc, 9.58,
facecolor='white', zorder=0,
clip_on=False, in_layout=False))
return ax
def create_text_axes(fig, height_px):
"""Create an Axes in *fig* that contains 'matplotlib' as Text."""
ax = fig.add_axes((0, 0, 1, 1))
ax.set_aspect("equal")
ax.set_axis_off()
path = TextPath((0, 0), "matplotlib", size=height_px * 0.8,
prop=get_font_properties())
angle = 4.25 # degrees
trans = mtrans.Affine2D().skew_deg(angle, 0)
patch = PathPatch(path, transform=trans + ax.transData, color=MPL_BLUE,
lw=0)
ax.add_patch(patch)
ax.autoscale()
def make_logo(height_px, lw_bars, lw_grid, lw_border, rgrid, with_text=False):
"""
Create a full figure with the Matplotlib logo.
Parameters
----------
height_px : int
Height of the figure in pixel.
lw_bars : float
The linewidth of the bar border.
lw_grid : float
The linewidth of the grid.
lw_border : float
The linewidth of icon border.
rgrid : sequence of float
The radial grid positions.
with_text : bool
Whether to draw only the icon or to include 'matplotlib' as text.
"""
dpi = 100
height = height_px / dpi
figsize = (5 * height, height) if with_text else (height, height)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
if with_text:
create_text_axes(fig, height_px)
ax_pos = (0.535, 0.12, .17, 0.75) if with_text else (0.03, 0.03, .94, .94)
ax = create_icon_axes(fig, ax_pos, lw_bars, lw_grid, lw_border, rgrid)
return fig, ax
# %%
# A large logo:
make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1,
rgrid=[1, 3, 5, 7])
# %%
# A small 32px logo:
make_logo(height_px=32, lw_bars=0.3, lw_grid=0.3, lw_border=0.3, rgrid=[5])
# %%
# A large logo including text, as used on the matplotlib website.
make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1,
rgrid=[1, 3, 5, 7], with_text=True)
plt.show()
| stable__gallery__misc__logos2 | 1 | figure_001.png | Matplotlib logo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/logos2.html#sphx-glr-download-gallery-misc-logos2-py | https://matplotlib.org/stable/_downloads/0846c3e5d114c457e124451aea9e558a/logos2.py | logos2.py | misc | ok | 3 | null | |
"""
===============
Matplotlib logo
===============
This example generates the current matplotlib logo.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.font_manager
from matplotlib.patches import PathPatch, Rectangle
from matplotlib.text import TextPath
import matplotlib.transforms as mtrans
MPL_BLUE = '#11557c'
def get_font_properties():
# The original font is Calibri, if that is not installed, we fall back
# to Carlito, which is metrically equivalent.
if 'Calibri' in matplotlib.font_manager.findfont('Calibri:bold'):
return matplotlib.font_manager.FontProperties(family='Calibri',
weight='bold')
if 'Carlito' in matplotlib.font_manager.findfont('Carlito:bold'):
print('Original font not found. Falling back to Carlito. '
'The logo text will not be in the correct font.')
return matplotlib.font_manager.FontProperties(family='Carlito',
weight='bold')
print('Original font not found. '
'The logo text will not be in the correct font.')
return None
def create_icon_axes(fig, ax_position, lw_bars, lw_grid, lw_border, rgrid):
"""
Create a polar Axes containing the matplotlib radar plot.
Parameters
----------
fig : matplotlib.figure.Figure
The figure to draw into.
ax_position : (float, float, float, float)
The position of the created Axes in figure coordinates as
(x, y, width, height).
lw_bars : float
The linewidth of the bars.
lw_grid : float
The linewidth of the grid.
lw_border : float
The linewidth of the Axes border.
rgrid : array-like
Positions of the radial grid.
Returns
-------
ax : matplotlib.axes.Axes
The created Axes.
"""
with plt.rc_context({'axes.edgecolor': MPL_BLUE,
'axes.linewidth': lw_border}):
ax = fig.add_axes(ax_position, projection='polar')
ax.set_axisbelow(True)
N = 7
arc = 2. * np.pi
theta = np.arange(0.0, arc, arc / N)
radii = np.array([2, 6, 8, 7, 4, 5, 8])
width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3])
bars = ax.bar(theta, radii, width=width, bottom=0.0, align='edge',
edgecolor='0.3', lw=lw_bars)
for r, bar in zip(radii, bars):
color = *cm.jet(r / 10.)[:3], 0.6 # color from jet with alpha=0.6
bar.set_facecolor(color)
ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
ax.grid(lw=lw_grid, color='0.9')
ax.set_rmax(9)
ax.set_yticks(rgrid)
# the actual visible background - extends a bit beyond the axis
ax.add_patch(Rectangle((0, 0), arc, 9.58,
facecolor='white', zorder=0,
clip_on=False, in_layout=False))
return ax
def create_text_axes(fig, height_px):
"""Create an Axes in *fig* that contains 'matplotlib' as Text."""
ax = fig.add_axes((0, 0, 1, 1))
ax.set_aspect("equal")
ax.set_axis_off()
path = TextPath((0, 0), "matplotlib", size=height_px * 0.8,
prop=get_font_properties())
angle = 4.25 # degrees
trans = mtrans.Affine2D().skew_deg(angle, 0)
patch = PathPatch(path, transform=trans + ax.transData, color=MPL_BLUE,
lw=0)
ax.add_patch(patch)
ax.autoscale()
def make_logo(height_px, lw_bars, lw_grid, lw_border, rgrid, with_text=False):
"""
Create a full figure with the Matplotlib logo.
Parameters
----------
height_px : int
Height of the figure in pixel.
lw_bars : float
The linewidth of the bar border.
lw_grid : float
The linewidth of the grid.
lw_border : float
The linewidth of icon border.
rgrid : sequence of float
The radial grid positions.
with_text : bool
Whether to draw only the icon or to include 'matplotlib' as text.
"""
dpi = 100
height = height_px / dpi
figsize = (5 * height, height) if with_text else (height, height)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)
if with_text:
create_text_axes(fig, height_px)
ax_pos = (0.535, 0.12, .17, 0.75) if with_text else (0.03, 0.03, .94, .94)
ax = create_icon_axes(fig, ax_pos, lw_bars, lw_grid, lw_border, rgrid)
return fig, ax
# %%
# A large logo:
make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1,
rgrid=[1, 3, 5, 7])
# %%
# A small 32px logo:
make_logo(height_px=32, lw_bars=0.3, lw_grid=0.3, lw_border=0.3, rgrid=[5])
# %%
# A large logo including text, as used on the matplotlib website.
make_logo(height_px=110, lw_bars=0.7, lw_grid=0.5, lw_border=1,
rgrid=[1, 3, 5, 7], with_text=True)
plt.show()
| stable__gallery__misc__logos2 | 2 | figure_002.png | Matplotlib logo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/logos2.html#sphx-glr-download-gallery-misc-logos2-py | https://matplotlib.org/stable/_downloads/0846c3e5d114c457e124451aea9e558a/logos2.py | logos2.py | misc | ok | 3 | null | |
"""
===================
Packed-bubble chart
===================
Create a packed-bubble chart to represent scalar data.
The presented algorithm tries to move all bubbles as close to the center of
mass as possible while avoiding some collisions by moving around colliding
objects. In this example we plot the market share of different desktop
browsers.
(source: https://gs.statcounter.com/browser-market-share/desktop/worldwidev)
"""
import matplotlib.pyplot as plt
import numpy as np
browser_market_share = {
'browsers': ['firefox', 'chrome', 'safari', 'edge', 'ie', 'opera'],
'market_share': [8.61, 69.55, 8.36, 4.12, 2.76, 2.43],
'color': ['#5A69AF', '#579E65', '#F9C784', '#FC944A', '#F24C00', '#00B825']
}
class BubbleChart:
def __init__(self, area, bubble_spacing=0):
"""
Setup for bubble collapse.
Parameters
----------
area : array-like
Area of the bubbles.
bubble_spacing : float, default: 0
Minimal spacing between bubbles after collapsing.
Notes
-----
If "area" is sorted, the results might look weird.
"""
area = np.asarray(area)
r = np.sqrt(area / np.pi)
self.bubble_spacing = bubble_spacing
self.bubbles = np.ones((len(area), 4))
self.bubbles[:, 2] = r
self.bubbles[:, 3] = area
self.maxstep = 2 * self.bubbles[:, 2].max() + self.bubble_spacing
self.step_dist = self.maxstep / 2
# calculate initial grid layout for bubbles
length = np.ceil(np.sqrt(len(self.bubbles)))
grid = np.arange(length) * self.maxstep
gx, gy = np.meshgrid(grid, grid)
self.bubbles[:, 0] = gx.flatten()[:len(self.bubbles)]
self.bubbles[:, 1] = gy.flatten()[:len(self.bubbles)]
self.com = self.center_of_mass()
def center_of_mass(self):
return np.average(
self.bubbles[:, :2], axis=0, weights=self.bubbles[:, 3]
)
def center_distance(self, bubble, bubbles):
return np.hypot(bubble[0] - bubbles[:, 0],
bubble[1] - bubbles[:, 1])
def outline_distance(self, bubble, bubbles):
center_distance = self.center_distance(bubble, bubbles)
return center_distance - bubble[2] - \
bubbles[:, 2] - self.bubble_spacing
def check_collisions(self, bubble, bubbles):
distance = self.outline_distance(bubble, bubbles)
return len(distance[distance < 0])
def collides_with(self, bubble, bubbles):
distance = self.outline_distance(bubble, bubbles)
return np.argmin(distance, keepdims=True)
def collapse(self, n_iterations=50):
"""
Move bubbles to the center of mass.
Parameters
----------
n_iterations : int, default: 50
Number of moves to perform.
"""
for _i in range(n_iterations):
moves = 0
for i in range(len(self.bubbles)):
rest_bub = np.delete(self.bubbles, i, 0)
# try to move directly towards the center of mass
# direction vector from bubble to the center of mass
dir_vec = self.com - self.bubbles[i, :2]
# shorten direction vector to have length of 1
dir_vec = dir_vec / np.sqrt(dir_vec.dot(dir_vec))
# calculate new bubble position
new_point = self.bubbles[i, :2] + dir_vec * self.step_dist
new_bubble = np.append(new_point, self.bubbles[i, 2:4])
# check whether new bubble collides with other bubbles
if not self.check_collisions(new_bubble, rest_bub):
self.bubbles[i, :] = new_bubble
self.com = self.center_of_mass()
moves += 1
else:
# try to move around a bubble that you collide with
# find colliding bubble
for colliding in self.collides_with(new_bubble, rest_bub):
# calculate direction vector
dir_vec = rest_bub[colliding, :2] - self.bubbles[i, :2]
dir_vec = dir_vec / np.sqrt(dir_vec.dot(dir_vec))
# calculate orthogonal vector
orth = np.array([dir_vec[1], -dir_vec[0]])
# test which direction to go
new_point1 = (self.bubbles[i, :2] + orth *
self.step_dist)
new_point2 = (self.bubbles[i, :2] - orth *
self.step_dist)
dist1 = self.center_distance(
self.com, np.array([new_point1]))
dist2 = self.center_distance(
self.com, np.array([new_point2]))
new_point = new_point1 if dist1 < dist2 else new_point2
new_bubble = np.append(new_point, self.bubbles[i, 2:4])
if not self.check_collisions(new_bubble, rest_bub):
self.bubbles[i, :] = new_bubble
self.com = self.center_of_mass()
if moves / len(self.bubbles) < 0.1:
self.step_dist = self.step_dist / 2
def plot(self, ax, labels, colors):
"""
Draw the bubble plot.
Parameters
----------
ax : matplotlib.axes.Axes
labels : list
Labels of the bubbles.
colors : list
Colors of the bubbles.
"""
for i in range(len(self.bubbles)):
circ = plt.Circle(
self.bubbles[i, :2], self.bubbles[i, 2], color=colors[i])
ax.add_patch(circ)
ax.text(*self.bubbles[i, :2], labels[i],
horizontalalignment='center', verticalalignment='center')
bubble_chart = BubbleChart(area=browser_market_share['market_share'],
bubble_spacing=0.1)
bubble_chart.collapse()
fig, ax = plt.subplots(subplot_kw=dict(aspect="equal"))
bubble_chart.plot(
ax, browser_market_share['browsers'], browser_market_share['color'])
ax.axis("off")
ax.relim()
ax.autoscale_view()
ax.set_title('Browser market share')
plt.show()
| stable__gallery__misc__packed_bubbles | 0 | figure_000.png | Packed-bubble chart — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/packed_bubbles.html#sphx-glr-download-gallery-misc-packed-bubbles-py | https://matplotlib.org/stable/_downloads/81bc179821dc9808604c256bcb20b3b0/packed_bubbles.py | packed_bubbles.py | misc | ok | 1 | null | |
"""
===============
Patheffect Demo
===============
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patheffects
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 3))
ax1.imshow([[1, 2], [2, 3]])
txt = ax1.annotate("test", (1., 1.), (0., 0),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3", lw=2),
size=20, ha="center",
path_effects=[patheffects.withStroke(linewidth=3,
foreground="w")])
txt.arrow_patch.set_path_effects([
patheffects.Stroke(linewidth=5, foreground="w"),
patheffects.Normal()])
pe = [patheffects.withStroke(linewidth=3,
foreground="w")]
ax1.grid(True, linestyle="-", path_effects=pe)
arr = np.arange(25).reshape((5, 5))
ax2.imshow(arr)
cntr = ax2.contour(arr, colors="k")
cntr.set(path_effects=[patheffects.withStroke(linewidth=3, foreground="w")])
clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
plt.setp(clbls, path_effects=[
patheffects.withStroke(linewidth=3, foreground="w")])
# shadow as a path effect
p1, = ax3.plot([0, 1], [0, 1])
leg = ax3.legend([p1], ["Line 1"], fancybox=True, loc='upper left')
leg.legendPatch.set_path_effects([patheffects.withSimplePatchShadow()])
plt.show()
| stable__gallery__misc__patheffect_demo | 0 | figure_000.png | Patheffect Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/patheffect_demo.html#sphx-glr-download-gallery-misc-patheffect-demo-py | https://matplotlib.org/stable/_downloads/1403c9176f441d71ec67e54e239b695e/patheffect_demo.py | patheffect_demo.py | misc | ok | 1 | null | |
"""
=================================
Rasterization for vector graphics
=================================
Rasterization converts vector graphics into a raster image (pixels). It can
speed up rendering and produce smaller files for large data sets, but comes
at the cost of a fixed resolution.
Whether rasterization should be used can be specified per artist. This can be
useful to reduce the file size of large artists, while maintaining the
advantages of vector graphics for other artists such as the Axes
and text. For instance a complicated `~.Axes.pcolormesh` or
`~.Axes.contourf` can be made significantly simpler by rasterizing.
Setting rasterization only affects vector backends such as PDF, SVG, or PS.
Rasterization is disabled by default. There are two ways to enable it, which
can also be combined:
- Set `~.Artist.set_rasterized` on individual artists, or use the keyword
argument *rasterized* when creating the artist.
- Set `.Axes.set_rasterization_zorder` to rasterize all artists with a zorder
less than the given value.
The storage size and the resolution of the rasterized artist is determined by
its physical size and the value of the ``dpi`` parameter passed to
`~.Figure.savefig`.
.. note::
The image of this example shown in the HTML documentation is not a vector
graphic. Therefore, it cannot illustrate the rasterization effect. Please
run this example locally and check the generated graphics files.
"""
import matplotlib.pyplot as plt
import numpy as np
d = np.arange(100).reshape(10, 10) # the values to be color-mapped
x, y = np.meshgrid(np.arange(11), np.arange(11))
theta = 0.25*np.pi
xx = x*np.cos(theta) - y*np.sin(theta) # rotate x by -theta
yy = x*np.sin(theta) + y*np.cos(theta) # rotate y by -theta
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, layout="constrained")
# pcolormesh without rasterization
ax1.set_aspect(1)
ax1.pcolormesh(xx, yy, d)
ax1.set_title("No Rasterization")
# pcolormesh with rasterization; enabled by keyword argument
ax2.set_aspect(1)
ax2.set_title("Rasterization")
ax2.pcolormesh(xx, yy, d, rasterized=True)
# pcolormesh with an overlaid text without rasterization
ax3.set_aspect(1)
ax3.pcolormesh(xx, yy, d)
ax3.text(0.5, 0.5, "Text", alpha=0.2,
va="center", ha="center", size=50, transform=ax3.transAxes)
ax3.set_title("No Rasterization")
# pcolormesh with an overlaid text without rasterization; enabled by zorder.
# Setting the rasterization zorder threshold to 0 and a negative zorder on the
# pcolormesh rasterizes it. All artists have a non-negative zorder by default,
# so they (e.g. the text here) are not affected.
ax4.set_aspect(1)
m = ax4.pcolormesh(xx, yy, d, zorder=-10)
ax4.text(0.5, 0.5, "Text", alpha=0.2,
va="center", ha="center", size=50, transform=ax4.transAxes)
ax4.set_rasterization_zorder(0)
ax4.set_title("Rasterization z$<-10$")
# Save files in pdf and eps format
plt.savefig("test_rasterization.pdf", dpi=150)
plt.savefig("test_rasterization.eps", dpi=150)
if not plt.rcParams["text.usetex"]:
plt.savefig("test_rasterization.svg", dpi=150)
# svg backend currently ignores the dpi
# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.artist.Artist.set_rasterized`
# - `matplotlib.axes.Axes.set_rasterization_zorder`
# - `matplotlib.axes.Axes.pcolormesh` / `matplotlib.pyplot.pcolormesh`
| stable__gallery__misc__rasterization_demo | 0 | figure_000.png | Rasterization for vector graphics — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/rasterization_demo.html#sphx-glr-download-gallery-misc-rasterization-demo-py | https://matplotlib.org/stable/_downloads/7aecd0ee1c8d945fad9779db5ebd3185/rasterization_demo.py | rasterization_demo.py | misc | ok | 1 | null | |
"""
======================
Set and get properties
======================
The pyplot interface allows you to use ``setp`` and ``getp`` to
set and get object properties respectively, as well as to do
introspection on the object.
Setting with ``setp``
=====================
To set the linestyle of a line to be dashed, you use ``setp``::
>>> line, = plt.plot([1, 2, 3])
>>> plt.setp(line, linestyle='--')
If you want to know the valid types of arguments, you can provide the
name of the property you want to set without a value::
>>> plt.setp(line, 'linestyle')
linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
If you want to see all the properties that can be set, and their
possible values, you can do::
>>> plt.setp(line)
``setp`` operates on a single instance or a list of instances. If you
are in query mode introspecting the possible values, only the first
instance in the sequence is used. When actually setting values, all
the instances will be set. For example, suppose you have a list of
two lines, the following will make both lines thicker and red::
>>> x = np.arange(0, 1, 0.01)
>>> y1 = np.sin(2*np.pi*x)
>>> y2 = np.sin(4*np.pi*x)
>>> lines = plt.plot(x, y1, x, y2)
>>> plt.setp(lines, linewidth=2, color='r')
Getting with ``getp``
=====================
``getp`` returns the value of a given attribute. You can use it to query
the value of a single attribute::
>>> plt.getp(line, 'linewidth')
0.5
or all the attribute/value pairs::
>>> plt.getp(line)
aa = True
alpha = 1.0
antialiased = True
c = b
clip_on = True
color = b
... long listing skipped ...
Aliases
=======
To reduce keystrokes in interactive mode, a number of properties
have short aliases, e.g., 'lw' for 'linewidth' and 'mec' for
'markeredgecolor'. When calling set or get in introspection mode,
these properties will be listed as 'fullname' or 'aliasname'.
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 1.0, 0.01)
y1 = np.sin(2*np.pi*x)
y2 = np.sin(4*np.pi*x)
lines = plt.plot(x, y1, x, y2)
l1, l2 = lines
plt.setp(lines, linestyle='--') # set both to dashed
plt.setp(l1, linewidth=2, color='r') # line1 is thick and red
plt.setp(l2, linewidth=1, color='g') # line2 is thinner and green
print('Line setters')
plt.setp(l1)
print('Line getters')
plt.getp(l1)
print('Rectangle setters')
plt.setp(plt.gca().patch)
print('Rectangle getters')
plt.getp(plt.gca().patch)
t = plt.title('Hi mom')
print('Text setters')
plt.setp(t)
print('Text getters')
plt.getp(t)
plt.show()
| stable__gallery__misc__set_and_get | 0 | figure_000.png | Set and get properties — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/set_and_get.html#sphx-glr-download-gallery-misc-set-and-get-py | https://matplotlib.org/stable/_downloads/1164b1c779f1bc16a7184125264f2b1a/set_and_get.py | set_and_get.py | misc | ok | 1 | null | |
"""
==========================
Apply SVG filter to a line
==========================
Demonstrate SVG filtering effects which might be used with Matplotlib.
Note that the filtering effects are only effective if your SVG renderer
support it.
"""
import io
import xml.etree.ElementTree as ET
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig1 = plt.figure()
ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
# draw lines
l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
mec="b", lw=5, ms=10, label="Line 1")
l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "rs-",
mec="r", lw=5, ms=10, label="Line 2")
for l in [l1, l2]:
# draw shadows with same lines with slight offset and gray colors.
xx = l.get_xdata()
yy = l.get_ydata()
shadow, = ax.plot(xx, yy)
shadow.update_from(l)
# adjust color
shadow.set_color("0.2")
# adjust zorder of the shadow lines so that it is drawn below the
# original lines
shadow.set_zorder(l.get_zorder() - 0.5)
# offset transform
transform = mtransforms.offset_copy(l.get_transform(), fig1,
x=4.0, y=-6.0, units='points')
shadow.set_transform(transform)
# set the id for a later use
shadow.set_gid(l.get_label() + "_shadow")
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
# save the figure as a bytes string in the svg format.
f = io.BytesIO()
plt.savefig(f, format="svg")
# filter definition for a gaussian blur
filter_def = """
<defs xmlns='http://www.w3.org/2000/svg'
xmlns:xlink='http://www.w3.org/1999/xlink'>
<filter id='dropshadow' height='1.2' width='1.2'>
<feGaussianBlur result='blur' stdDeviation='3'/>
</filter>
</defs>
"""
# read in the saved svg
tree, xmlid = ET.XMLID(f.getvalue())
# insert the filter definition in the svg dom tree.
tree.insert(0, ET.XML(filter_def))
for l in [l1, l2]:
# pick up the svg element with given id
shadow = xmlid[l.get_label() + "_shadow"]
# apply shadow filter
shadow.set("filter", 'url(#dropshadow)')
fn = "svg_filter_line.svg"
print(f"Saving '{fn}'")
ET.ElementTree(tree).write(fn)
| stable__gallery__misc__svg_filter_line | 0 | figure_000.png | Apply SVG filter to a line — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/svg_filter_line.html#sphx-glr-download-gallery-misc-svg-filter-line-py | https://matplotlib.org/stable/_downloads/9f8aa7731c3c1bf0306b6dce55bacda0/svg_filter_line.py | svg_filter_line.py | misc | ok | 1 | null | |
"""
==============
SVG filter pie
==============
Demonstrate SVG filtering effects which might be used with Matplotlib.
The pie chart drawing code is borrowed from pie_demo.py
Note that the filtering effects are only effective if your SVG renderer
support it.
"""
import io
import xml.etree.ElementTree as ET
import matplotlib.pyplot as plt
from matplotlib.patches import Shadow
# make a square figure and Axes
fig = plt.figure(figsize=(6, 6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
# We want to draw the shadow for each pie, but we will not use "shadow"
# option as it doesn't save the references to the shadow patches.
pies = ax.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%')
for w in pies[0]:
# set the id with the label.
w.set_gid(w.get_label())
# we don't want to draw the edge of the pie
w.set_edgecolor("none")
for w in pies[0]:
# create shadow patch
s = Shadow(w, -0.01, -0.01)
s.set_gid(w.get_gid() + "_shadow")
s.set_zorder(w.get_zorder() - 0.1)
ax.add_patch(s)
# save
f = io.BytesIO()
plt.savefig(f, format="svg")
# Filter definition for shadow using a gaussian blur and lighting effect.
# The lighting filter is copied from http://www.w3.org/TR/SVG/filters.html
# I tested it with Inkscape and Firefox3. "Gaussian blur" is supported
# in both, but the lighting effect only in Inkscape. Also note
# that, Inkscape's exporting also may not support it.
filter_def = """
<defs xmlns='http://www.w3.org/2000/svg'
xmlns:xlink='http://www.w3.org/1999/xlink'>
<filter id='dropshadow' height='1.2' width='1.2'>
<feGaussianBlur result='blur' stdDeviation='2'/>
</filter>
<filter id='MyFilter' filterUnits='objectBoundingBox'
x='0' y='0' width='1' height='1'>
<feGaussianBlur in='SourceAlpha' stdDeviation='4%' result='blur'/>
<feOffset in='blur' dx='4%' dy='4%' result='offsetBlur'/>
<feSpecularLighting in='blur' surfaceScale='5' specularConstant='.75'
specularExponent='20' lighting-color='#bbbbbb' result='specOut'>
<fePointLight x='-5000%' y='-10000%' z='20000%'/>
</feSpecularLighting>
<feComposite in='specOut' in2='SourceAlpha'
operator='in' result='specOut'/>
<feComposite in='SourceGraphic' in2='specOut' operator='arithmetic'
k1='0' k2='1' k3='1' k4='0'/>
</filter>
</defs>
"""
tree, xmlid = ET.XMLID(f.getvalue())
# insert the filter definition in the svg dom tree.
tree.insert(0, ET.XML(filter_def))
for i, pie_name in enumerate(labels):
pie = xmlid[pie_name]
pie.set("filter", 'url(#MyFilter)')
shadow = xmlid[pie_name + "_shadow"]
shadow.set("filter", 'url(#dropshadow)')
fn = "svg_filter_pie.svg"
print(f"Saving '{fn}'")
ET.ElementTree(tree).write(fn)
| stable__gallery__misc__svg_filter_pie | 0 | figure_000.png | SVG filter pie — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/svg_filter_pie.html#svg-filter-pie | https://matplotlib.org/stable/_downloads/15ebd41aec6ebf084ad5797ba93359e4/svg_filter_pie.py | svg_filter_pie.py | misc | ok | 1 | null | |
"""
==========
Table Demo
==========
Demo of table function to display a table within a plot.
"""
import matplotlib.pyplot as plt
import numpy as np
data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[139361, 331509, 343164, 781380, 52269]]
columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]
values = np.arange(0, 2500, 500)
value_increment = 1000
# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
n_rows = len(data)
index = np.arange(len(columns)) + 0.3
bar_width = 0.4
# Initialize the vertical-offset for the stacked bar chart.
y_offset = np.zeros(len(columns))
# Plot bars and create text labels for the table
cell_text = []
for row in range(n_rows):
plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
cell_text.reverse()
# Add a table at the bottom of the Axes
the_table = plt.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
loc='bottom')
# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.2, bottom=0.2)
plt.ylabel(f"Loss in ${value_increment}'s")
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')
plt.show()
| stable__gallery__misc__table_demo | 0 | figure_000.png | Table Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/table_demo.html#table-demo | https://matplotlib.org/stable/_downloads/017058e784e2a359b3a7dd004a3e0379/table_demo.py | table_demo.py | misc | ok | 1 | null | |
"""
=======================
TickedStroke patheffect
=======================
Matplotlib's :mod:`.patheffects` can be used to alter the way paths
are drawn at a low enough level that they can affect almost anything.
The :ref:`patheffects guide<patheffects_guide>`
details the use of patheffects.
The `~matplotlib.patheffects.TickedStroke` patheffect illustrated here
draws a path with a ticked style. The spacing, length, and angle of
ticks can be controlled.
See also the :doc:`/gallery/lines_bars_and_markers/lines_with_ticks_demo` example.
See also the :doc:`/gallery/images_contours_and_fields/contours_in_optimization_demo`
example.
"""
import matplotlib.pyplot as plt
import numpy as np
# %%
# Applying TickedStroke to paths
# ==============================
import matplotlib.patches as patches
from matplotlib.path import Path
import matplotlib.patheffects as patheffects
fig, ax = plt.subplots(figsize=(6, 6))
path = Path.unit_circle()
patch = patches.PathPatch(path, facecolor='none', lw=2, path_effects=[
patheffects.withTickedStroke(angle=-90, spacing=10, length=1)])
ax.add_patch(patch)
ax.axis('equal')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
plt.show()
# %%
# Applying TickedStroke to lines
# ==============================
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot([0, 1], [0, 1], label="Line",
path_effects=[patheffects.withTickedStroke(spacing=7, angle=135)])
nx = 101
x = np.linspace(0.0, 1.0, nx)
y = 0.3*np.sin(x*8) + 0.4
ax.plot(x, y, label="Curve", path_effects=[patheffects.withTickedStroke()])
ax.legend()
plt.show()
# %%
# Applying TickedStroke to contour plots
# ======================================
#
# Contour plot with objective and constraints.
# Curves generated by contour to represent a typical constraint in an
# optimization problem should be plotted with angles between zero and
# 180 degrees.
fig, ax = plt.subplots(figsize=(6, 6))
nx = 101
ny = 105
# Set up survey vectors
xvec = np.linspace(0.001, 4.0, nx)
yvec = np.linspace(0.001, 4.0, ny)
# Set up survey matrices. Design disk loading and gear ratio.
x1, x2 = np.meshgrid(xvec, yvec)
# Evaluate some stuff to plot
obj = x1**2 + x2**2 - 2*x1 - 2*x2 + 2
g1 = -(3*x1 + x2 - 5.5)
g2 = -(x1 + 2*x2 - 4.5)
g3 = 0.8 + x1**-3 - x2
cntr = ax.contour(x1, x2, obj, [0.01, 0.1, 0.5, 1, 2, 4, 8, 16],
colors='black')
ax.clabel(cntr, fmt="%2.1f", use_clabeltext=True)
cg1 = ax.contour(x1, x2, g1, [0], colors='sandybrown')
cg1.set(path_effects=[patheffects.withTickedStroke(angle=135)])
cg2 = ax.contour(x1, x2, g2, [0], colors='orangered')
cg2.set(path_effects=[patheffects.withTickedStroke(angle=60, length=2)])
cg3 = ax.contour(x1, x2, g3, [0], colors='mediumblue')
cg3.set(path_effects=[patheffects.withTickedStroke(spacing=7)])
ax.set_xlim(0, 4)
ax.set_ylim(0, 4)
plt.show()
# %%
# Direction/side of the ticks
# ===========================
#
# To change which side of the line the ticks are drawn, change the sign of the angle.
fig, ax = plt.subplots(figsize=(6, 6))
line_x = line_y = [0, 1]
ax.plot(line_x, line_y, label="Line",
path_effects=[patheffects.withTickedStroke(spacing=7, angle=135)])
ax.plot(line_x, line_y, label="Opposite side",
path_effects=[patheffects.withTickedStroke(spacing=7, angle=-135)])
ax.legend()
plt.show()
| stable__gallery__misc__tickedstroke_demo | 0 | figure_000.png | TickedStroke patheffect — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/tickedstroke_demo.html#tickedstroke-patheffect | https://matplotlib.org/stable/_downloads/ee238568c97acaa88c1fecf30916a9a7/tickedstroke_demo.py | tickedstroke_demo.py | misc | ok | 4 | null | |
"""
======================
transforms.offset_copy
======================
This illustrates the use of `.transforms.offset_copy` to
make a transform that positions a drawing element such as
a text string at a specified offset in screen coordinates
(dots or inches) relative to a location given in any
coordinates.
Every Artist (Text, Line2D, etc.) has a transform that can be
set when the Artist is created, such as by the corresponding
pyplot function. By default, this is usually the Axes.transData
transform, going from data units to screen pixels. We can
use the `.offset_copy` function to make a modified copy of
this transform, where the modification consists of an
offset.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms as mtransforms
xs = np.arange(7)
ys = xs**2
fig = plt.figure(figsize=(5, 10))
ax = plt.subplot(2, 1, 1)
# If we want the same offset for each text instance,
# we only need to make one transform. To get the
# transform argument to offset_copy, we need to make the Axes
# first; the subplot function above is one way to do this.
trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
x=0.05, y=0.10, units='inches')
for x, y in zip(xs, ys):
plt.plot(x, y, 'ro')
plt.text(x, y, '%d, %d' % (int(x), int(y)), transform=trans_offset)
# offset_copy works for polar plots also.
ax = plt.subplot(2, 1, 2, projection='polar')
trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
y=6, units='dots')
for x, y in zip(xs, ys):
plt.polar(x, y, 'ro')
plt.text(x, y, '%d, %d' % (int(x), int(y)),
transform=trans_offset,
horizontalalignment='center',
verticalalignment='bottom')
plt.show()
| stable__gallery__misc__transoffset | 0 | figure_000.png | transforms.offset_copy — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/transoffset.html#transforms-offset-copy | https://matplotlib.org/stable/_downloads/51f71780b1f0e8c2b3d14e33ae33f05f/transoffset.py | transoffset.py | misc | ok | 1 | null | |
"""
===========
Zorder Demo
===========
The drawing order of artists is determined by their ``zorder`` attribute, which
is a floating point number. Artists with higher ``zorder`` are drawn on top.
You can change the order for individual artists by setting their ``zorder``.
The default value depends on the type of the Artist:
================================================================ =======
Artist Z-order
================================================================ =======
Images (`.AxesImage`, `.FigureImage`, `.BboxImage`) 0
`.Patch`, `.PatchCollection` 1
`.Line2D`, `.LineCollection` (including minor ticks, grid lines) 2
Major ticks 2.01
`.Text` (including Axes labels and titles) 3
`.Legend` 5
================================================================ =======
Any call to a plotting method can set a value for the zorder of that particular
item explicitly.
.. note::
`~.axes.Axes.set_axisbelow` and :rc:`axes.axisbelow` are convenient helpers
for setting the zorder of ticks and grid lines.
Drawing is done per `~.axes.Axes` at a time. If you have overlapping Axes, all
elements of the second Axes are drawn on top of the first Axes, irrespective of
their relative zorder.
"""
import matplotlib.pyplot as plt
import numpy as np
r = np.linspace(0.3, 1, 30)
theta = np.linspace(0, 4*np.pi, 30)
x = r * np.sin(theta)
y = r * np.cos(theta)
# %%
# The following example contains a `.Line2D` created by `~.axes.Axes.plot()`
# and the dots (a `.PatchCollection`) created by `~.axes.Axes.scatter()`.
# Hence, by default the dots are below the line (first subplot).
# In the second subplot, the ``zorder`` is set explicitly to move the dots
# on top of the line.
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3.2))
ax1.plot(x, y, 'C3', lw=3)
ax1.scatter(x, y, s=120)
ax1.set_title('Lines on top of dots')
ax2.plot(x, y, 'C3', lw=3)
ax2.scatter(x, y, s=120, zorder=2.5) # move dots on top of line
ax2.set_title('Dots on top of lines')
plt.tight_layout()
# %%
# Many functions that create a visible object accepts a ``zorder`` parameter.
# Alternatively, you can call ``set_zorder()`` on the created object later.
x = np.linspace(0, 7.5, 100)
plt.rcParams['lines.linewidth'] = 5
plt.figure()
plt.plot(x, np.sin(x), label='zorder=2', zorder=2) # bottom
plt.plot(x, np.sin(x+0.5), label='zorder=3', zorder=3)
plt.axhline(0, label='zorder=2.5', color='lightgrey', zorder=2.5)
plt.title('Custom order of elements')
l = plt.legend(loc='upper right')
l.set_zorder(2.5) # legend between blue and orange line
plt.show()
| stable__gallery__misc__zorder_demo | 0 | figure_000.png | Zorder Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/zorder_demo.html#zorder-demo | https://matplotlib.org/stable/_downloads/1f573e76544733470b40b7cc1018cdb9/zorder_demo.py | zorder_demo.py | misc | ok | 2 | null | |
"""
===========
Zorder Demo
===========
The drawing order of artists is determined by their ``zorder`` attribute, which
is a floating point number. Artists with higher ``zorder`` are drawn on top.
You can change the order for individual artists by setting their ``zorder``.
The default value depends on the type of the Artist:
================================================================ =======
Artist Z-order
================================================================ =======
Images (`.AxesImage`, `.FigureImage`, `.BboxImage`) 0
`.Patch`, `.PatchCollection` 1
`.Line2D`, `.LineCollection` (including minor ticks, grid lines) 2
Major ticks 2.01
`.Text` (including Axes labels and titles) 3
`.Legend` 5
================================================================ =======
Any call to a plotting method can set a value for the zorder of that particular
item explicitly.
.. note::
`~.axes.Axes.set_axisbelow` and :rc:`axes.axisbelow` are convenient helpers
for setting the zorder of ticks and grid lines.
Drawing is done per `~.axes.Axes` at a time. If you have overlapping Axes, all
elements of the second Axes are drawn on top of the first Axes, irrespective of
their relative zorder.
"""
import matplotlib.pyplot as plt
import numpy as np
r = np.linspace(0.3, 1, 30)
theta = np.linspace(0, 4*np.pi, 30)
x = r * np.sin(theta)
y = r * np.cos(theta)
# %%
# The following example contains a `.Line2D` created by `~.axes.Axes.plot()`
# and the dots (a `.PatchCollection`) created by `~.axes.Axes.scatter()`.
# Hence, by default the dots are below the line (first subplot).
# In the second subplot, the ``zorder`` is set explicitly to move the dots
# on top of the line.
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3.2))
ax1.plot(x, y, 'C3', lw=3)
ax1.scatter(x, y, s=120)
ax1.set_title('Lines on top of dots')
ax2.plot(x, y, 'C3', lw=3)
ax2.scatter(x, y, s=120, zorder=2.5) # move dots on top of line
ax2.set_title('Dots on top of lines')
plt.tight_layout()
# %%
# Many functions that create a visible object accepts a ``zorder`` parameter.
# Alternatively, you can call ``set_zorder()`` on the created object later.
x = np.linspace(0, 7.5, 100)
plt.rcParams['lines.linewidth'] = 5
plt.figure()
plt.plot(x, np.sin(x), label='zorder=2', zorder=2) # bottom
plt.plot(x, np.sin(x+0.5), label='zorder=3', zorder=3)
plt.axhline(0, label='zorder=2.5', color='lightgrey', zorder=2.5)
plt.title('Custom order of elements')
l = plt.legend(loc='upper right')
l.set_zorder(2.5) # legend between blue and orange line
plt.show()
| stable__gallery__misc__zorder_demo | 1 | figure_001.png | Zorder Demo — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/misc/zorder_demo.html#zorder-demo | https://matplotlib.org/stable/_downloads/1f573e76544733470b40b7cc1018cdb9/zorder_demo.py | zorder_demo.py | misc | ok | 2 | null | |
"""
=======================
Plot 2D data on 3D plot
=======================
Demonstrates using ax.plot's *zdir* keyword to plot 2D data on
selective axes of a 3D plot.
"""
import matplotlib.pyplot as plt
import numpy as np
ax = plt.figure().add_subplot(projection='3d')
# Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x, y)')
# Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
c_list.extend([c] * 20)
# By using zdir='y', the y value of these points is fixed to the zs value 0
# and the (x, y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x, z)')
# Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Customize the view angle so it's easier to see that the scatter points lie
# on the plane y=0
ax.view_init(elev=20., azim=-35, roll=0)
plt.show()
# %%
# .. tags::
# plot-type: 3D, plot-type: scatter, plot-type: line,
# component: axes,
# level: intermediate
| stable__gallery__mplot3d__2dcollections3d | 0 | figure_000.png | Plot 2D data on 3D plot — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/2dcollections3d.html#sphx-glr-download-gallery-mplot3d-2dcollections3d-py | https://matplotlib.org/stable/_downloads/82806b819d5516f91bb92a2c94296201/2dcollections3d.py | 2dcollections3d.py | mplot3d | ok | 1 | null | |
"""
=====================
Demo of 3D bar charts
=====================
A basic demo of how to plot 3D bars with and without shading.
"""
import matplotlib.pyplot as plt
import numpy as np
# set up the figure and Axes
fig = plt.figure(figsize=(8, 3))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')
# fake data
_x = np.arange(4)
_y = np.arange(5)
_xx, _yy = np.meshgrid(_x, _y)
x, y = _xx.ravel(), _yy.ravel()
top = x + y
bottom = np.zeros_like(top)
width = depth = 1
ax1.bar3d(x, y, bottom, width, depth, top, shade=True)
ax1.set_title('Shaded')
ax2.bar3d(x, y, bottom, width, depth, top, shade=False)
ax2.set_title('Not Shaded')
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# styling: texture,
# plot-type: bar,
# level: beginner
| stable__gallery__mplot3d__3d_bars | 0 | figure_000.png | Demo of 3D bar charts — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/3d_bars.html#sphx-glr-download-gallery-mplot3d-3d-bars-py | https://matplotlib.org/stable/_downloads/b2426003d482f6dc8125fd971aafd3d4/3d_bars.py | 3d_bars.py | mplot3d | ok | 1 | null | |
"""
=====================================
Clip the data to the axes view limits
=====================================
Demonstrate clipping of line and marker data to the axes view limits. The
``axlim_clip`` keyword argument can be used in any of the 3D plotting
functions.
"""
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
# Make the data
x = np.arange(-5, 5, 0.5)
y = np.arange(-5, 5, 0.5)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# Default behavior is axlim_clip=False
ax.plot_wireframe(X, Y, Z, color='C0')
# When axlim_clip=True, note that when a line segment has one vertex outside
# the view limits, the entire line is hidden. The same is true for 3D patches
# if one of their vertices is outside the limits (not shown).
ax.plot_wireframe(X, Y, Z, color='C1', axlim_clip=True)
# In this example, data where x < 0 or z > 0.5 is clipped
ax.set(xlim=(0, 10), ylim=(-5, 5), zlim=(-1, 0.5))
ax.legend(['axlim_clip=False (default)', 'axlim_clip=True'])
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: beginner
| stable__gallery__mplot3d__axlim_clip | 0 | figure_000.png | Clip the data to the axes view limits — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/axlim_clip.html#sphx-glr-download-gallery-mplot3d-axlim-clip-py | https://matplotlib.org/stable/_downloads/69439e0cb9599c9022501fdf410371ff/axlim_clip.py | axlim_clip.py | mplot3d | ok | 1 | null | |
"""
========================================
Create 2D bar graphs in different planes
========================================
Demonstrates making a 3D plot which has 2D bar graphs projected onto
planes y=0, y=1, etc.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
colors = ['r', 'g', 'b', 'y']
yticks = [3, 2, 1, 0]
for c, k in zip(colors, yticks):
# Generate the random data for the y=k 'layer'.
xs = np.arange(20)
ys = np.random.rand(20)
# You can provide either a single color or an array with the same length as
# xs and ys. To demonstrate this, we color the first bar of each set cyan.
cs = [c] * len(xs)
cs[0] = 'c'
# Plot the bar graph given by xs and ys on the plane y=k with 80% opacity.
ax.bar(xs, ys, zs=k, zdir='y', color=cs, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# On the y-axis let's only label the discrete values that we have data for.
ax.set_yticks(yticks)
plt.show()
# %%
# .. tags::
# plot-type: 3D, plot-type: bar,
# styling: color,
# level: beginner
| stable__gallery__mplot3d__bars3d | 0 | figure_000.png | Create 2D bar graphs in different planes — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/bars3d.html#sphx-glr-download-gallery-mplot3d-bars3d-py | https://matplotlib.org/stable/_downloads/5b023f7fea1b0a1fc6abfea4090951a1/bars3d.py | bars3d.py | mplot3d | ok | 1 | null | |
"""
===================
3D box surface plot
===================
Given data on a gridded volume ``X``, ``Y``, ``Z``, this example plots the
data values on the volume surfaces.
The strategy is to select the data from each surface and plot
contours separately using `.axes3d.Axes3D.contourf` with appropriate
parameters *zdir* and *offset*.
"""
import matplotlib.pyplot as plt
import numpy as np
# Define dimensions
Nx, Ny, Nz = 100, 300, 500
X, Y, Z = np.meshgrid(np.arange(Nx), np.arange(Ny), -np.arange(Nz))
# Create fake data
data = (((X+100)**2 + (Y-20)**2 + 2*Z)/1000+1)
kw = {
'vmin': data.min(),
'vmax': data.max(),
'levels': np.linspace(data.min(), data.max(), 10),
}
# Create a figure with 3D ax
fig = plt.figure(figsize=(5, 4))
ax = fig.add_subplot(111, projection='3d')
# Plot contour surfaces
_ = ax.contourf(
X[:, :, 0], Y[:, :, 0], data[:, :, 0],
zdir='z', offset=0, **kw
)
_ = ax.contourf(
X[0, :, :], data[0, :, :], Z[0, :, :],
zdir='y', offset=0, **kw
)
C = ax.contourf(
data[:, -1, :], Y[:, -1, :], Z[:, -1, :],
zdir='x', offset=X.max(), **kw
)
# --
# Set limits of the plot from coord limits
xmin, xmax = X.min(), X.max()
ymin, ymax = Y.min(), Y.max()
zmin, zmax = Z.min(), Z.max()
ax.set(xlim=[xmin, xmax], ylim=[ymin, ymax], zlim=[zmin, zmax])
# Plot edges
edges_kw = dict(color='0.4', linewidth=1, zorder=1e3)
ax.plot([xmax, xmax], [ymin, ymax], 0, **edges_kw)
ax.plot([xmin, xmax], [ymin, ymin], 0, **edges_kw)
ax.plot([xmax, xmax], [ymin, ymin], [zmin, zmax], **edges_kw)
# Set labels and zticks
ax.set(
xlabel='X [km]',
ylabel='Y [km]',
zlabel='Z [m]',
zticks=[0, -150, -300, -450],
)
# Set zoom and angle view
ax.view_init(40, -30, 0)
ax.set_box_aspect(None, zoom=0.9)
# Colorbar
fig.colorbar(C, ax=ax, fraction=0.02, pad=0.1, label='Name [units]')
# Show Figure
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: intermediate
| stable__gallery__mplot3d__box3d | 0 | figure_000.png | 3D box surface plot — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/box3d.html#sphx-glr-download-gallery-mplot3d-box3d-py | https://matplotlib.org/stable/_downloads/2f55e7d3c6f1f46dcc05e217087e84df/box3d.py | box3d.py | mplot3d | ok | 1 | null | |
"""
=================================
Plot contour (level) curves in 3D
=================================
This is like a contour plot in 2D except that the ``f(x, y)=c`` curve is
plotted on the plane ``z=c``.
"""
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.contour(X, Y, Z, cmap=cm.coolwarm) # Plot contour curves
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: beginner
| stable__gallery__mplot3d__contour3d | 0 | figure_000.png | Plot contour (level) curves in 3D — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/contour3d.html#sphx-glr-download-gallery-mplot3d-contour3d-py | https://matplotlib.org/stable/_downloads/6989ade00e7a8f65a6687d825416ba7c/contour3d.py | contour3d.py | mplot3d | ok | 1 | null | |
"""
===========================================================
Plot contour (level) curves in 3D using the extend3d option
===========================================================
This modification of the :doc:`contour3d` example uses ``extend3d=True`` to
extend the curves vertically into 'ribbons'.
"""
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.contour(X, Y, Z, extend3d=True, cmap=cm.coolwarm)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: beginner
| stable__gallery__mplot3d__contour3d_2 | 0 | figure_000.png | Plot contour (level) curves in 3D using the extend3d option — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/contour3d_2.html#sphx-glr-download-gallery-mplot3d-contour3d-2-py | https://matplotlib.org/stable/_downloads/1531a5c0cde762fac88bcce62a5bdefc/contour3d_2.py | contour3d_2.py | mplot3d | ok | 1 | null | |
"""
=====================================
Project contour profiles onto a graph
=====================================
Demonstrates displaying a 3D surface while also projecting contour 'profiles'
onto the 'walls' of the graph.
See :doc:`contourf3d_2` for the filled version.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
# Plot the 3D surface
ax.plot_surface(X, Y, Z, edgecolor='royalblue', lw=0.5, rstride=8, cstride=8,
alpha=0.3)
# Plot projections of the contours for each dimension. By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph.
ax.contour(X, Y, Z, zdir='z', offset=-100, cmap='coolwarm')
ax.contour(X, Y, Z, zdir='x', offset=-40, cmap='coolwarm')
ax.contour(X, Y, Z, zdir='y', offset=40, cmap='coolwarm')
ax.set(xlim=(-40, 40), ylim=(-40, 40), zlim=(-100, 100),
xlabel='X', ylabel='Y', zlabel='Z')
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# component: axes,
# level: intermediate
| stable__gallery__mplot3d__contour3d_3 | 0 | figure_000.png | Project contour profiles onto a graph — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/contour3d_3.html#sphx-glr-download-gallery-mplot3d-contour3d-3-py | https://matplotlib.org/stable/_downloads/b38e7e6affb8627f98fe832e54458e99/contour3d_3.py | contour3d_3.py | mplot3d | ok | 1 | null | |
"""
===============
Filled contours
===============
`.Axes3D.contourf` differs from `.Axes3D.contour` in that it creates filled
contours, i.e. a discrete number of colours are used to shade the domain.
This is like a `.Axes.contourf` plot in 2D except that the shaded region
corresponding to the level c is graphed on the plane ``z=c``.
"""
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d
ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.contourf(X, Y, Z, cmap=cm.coolwarm)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: beginner
| stable__gallery__mplot3d__contourf3d | 0 | figure_000.png | Filled contours — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/contourf3d.html#sphx-glr-download-gallery-mplot3d-contourf3d-py | https://matplotlib.org/stable/_downloads/d441affd37b47c7dcc7eb8b36352778e/contourf3d.py | contourf3d.py | mplot3d | ok | 1 | null | |
"""
===================================
Project filled contour onto a graph
===================================
Demonstrates displaying a 3D surface while also projecting filled contour
'profiles' onto the 'walls' of the graph.
See :doc:`contour3d_3` for the unfilled version.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
# Plot the 3D surface
ax.plot_surface(X, Y, Z, edgecolor='royalblue', lw=0.5, rstride=8, cstride=8,
alpha=0.3)
# Plot projections of the contours for each dimension. By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph
ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap='coolwarm')
ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap='coolwarm')
ax.contourf(X, Y, Z, zdir='y', offset=40, cmap='coolwarm')
ax.set(xlim=(-40, 40), ylim=(-40, 40), zlim=(-100, 100),
xlabel='X', ylabel='Y', zlabel='Z')
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# component: axes,
# level: intermediate
| stable__gallery__mplot3d__contourf3d_2 | 0 | figure_000.png | Project filled contour onto a graph — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/contourf3d_2.html#sphx-glr-download-gallery-mplot3d-contourf3d-2-py | https://matplotlib.org/stable/_downloads/397c15d5008710bca03d5708217557c0/contourf3d_2.py | contourf3d_2.py | mplot3d | ok | 1 | null | |
"""
=======================================
Custom hillshading in a 3D surface plot
=======================================
Demonstrates using custom hillshading in a 3D surface plot.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cbook, cm
from matplotlib.colors import LightSource
# Load and format data
dem = cbook.get_sample_data('jacksboro_fault_dem.npz')
z = dem['elevation']
nrows, ncols = z.shape
x = np.linspace(dem['xmin'], dem['xmax'], ncols)
y = np.linspace(dem['ymin'], dem['ymax'], nrows)
x, y = np.meshgrid(x, y)
region = np.s_[5:50, 5:50]
x, y, z = x[region], y[region], z[region]
# Set up plot
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
ls = LightSource(270, 45)
# To use a custom hillshading mode, override the built-in shading and pass
# in the rgb colors of the shaded surface calculated from "shade".
rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb,
linewidth=0, antialiased=False, shade=False)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: intermediate,
# domain: cartography
| stable__gallery__mplot3d__custom_shaded_3d_surface | 0 | figure_000.png | Custom hillshading in a 3D surface plot — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/custom_shaded_3d_surface.html#sphx-glr-download-gallery-mplot3d-custom-shaded-3d-surface-py | https://matplotlib.org/stable/_downloads/3b9ac21ecf6a0b30550b0fb236dcec5a/custom_shaded_3d_surface.py | custom_shaded_3d_surface.py | mplot3d | ok | 1 | null | |
"""
============
3D errorbars
============
An example of using errorbars with upper and lower limits in mplot3d.
"""
import matplotlib.pyplot as plt
import numpy as np
ax = plt.figure().add_subplot(projection='3d')
# setting up a parametric curve
t = np.arange(0, 2*np.pi+.1, 0.01)
x, y, z = np.sin(t), np.cos(3*t), np.sin(5*t)
estep = 15
i = np.arange(t.size)
zuplims = (i % estep == 0) & (i // estep % 3 == 0)
zlolims = (i % estep == 0) & (i // estep % 3 == 2)
ax.errorbar(x, y, z, 0.2, zuplims=zuplims, zlolims=zlolims, errorevery=estep)
ax.set_xlabel("X label")
ax.set_ylabel("Y label")
ax.set_zlabel("Z label")
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# component: error,
# level: beginner
| stable__gallery__mplot3d__errorbar3d | 0 | figure_000.png | 3D errorbars — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/errorbar3d.html#sphx-glr-download-gallery-mplot3d-errorbar3d-py | https://matplotlib.org/stable/_downloads/7393bf5548239a03c1f437616d7da22e/errorbar3d.py | errorbar3d.py | mplot3d | ok | 1 | null | |
"""
=====================
Fill between 3D lines
=====================
Demonstrate how to fill the space between 3D lines with surfaces. Here we
create a sort of "lampshade" shape.
"""
import matplotlib.pyplot as plt
import numpy as np
N = 50
theta = np.linspace(0, 2*np.pi, N)
x1 = np.cos(theta)
y1 = np.sin(theta)
z1 = 0.1 * np.sin(6 * theta)
x2 = 0.6 * np.cos(theta)
y2 = 0.6 * np.sin(theta)
z2 = 2 # Note that scalar values work in addition to length N arrays
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.fill_between(x1, y1, z1, x2, y2, z2, alpha=0.5, edgecolor='k')
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# plot-type: fill_between,
# level: beginner
| stable__gallery__mplot3d__fillbetween3d | 0 | figure_000.png | Fill between 3D lines — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/fillbetween3d.html#sphx-glr-download-gallery-mplot3d-fillbetween3d-py | https://matplotlib.org/stable/_downloads/95d823ebdf4a1590b38e6c3ba1874be8/fillbetween3d.py | fillbetween3d.py | mplot3d | ok | 1 | null | |
"""
=========================
Fill under 3D line graphs
=========================
Demonstrate how to create polygons which fill the space under a line
graph. In this example polygons are semi-transparent, creating a sort
of 'jagged stained glass' effect.
"""
import math
import matplotlib.pyplot as plt
import numpy as np
gamma = np.vectorize(math.gamma)
N = 31
x = np.linspace(0., 10., N)
lambdas = range(1, 9)
ax = plt.figure().add_subplot(projection='3d')
facecolors = plt.colormaps['viridis_r'](np.linspace(0, 1, len(lambdas)))
for i, l in enumerate(lambdas):
# Note fill_between can take coordinates as length N vectors, or scalars
ax.fill_between(x, l, l**x * np.exp(-l) / gamma(x + 1),
x, l, 0,
facecolors=facecolors[i], alpha=.7)
ax.set(xlim=(0, 10), ylim=(1, 9), zlim=(0, 0.35),
xlabel='x', ylabel=r'$\lambda$', zlabel='probability')
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# plot-type: fill_between,
# level: beginner
| stable__gallery__mplot3d__fillunder3d | 0 | figure_000.png | Fill under 3D line graphs — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/fillunder3d.html#sphx-glr-download-gallery-mplot3d-fillunder3d-py | https://matplotlib.org/stable/_downloads/76b7ceeb0e946ed74946217ca457ef89/fillunder3d.py | fillunder3d.py | mplot3d | ok | 1 | null | |
"""
==============================
Create 3D histogram of 2D data
==============================
Demo of a histogram for 2D data as a bar graph in 3D.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])
# Construct arrays for the anchor positions of the 16 bars.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij")
xpos = xpos.ravel()
ypos = ypos.ravel()
zpos = 0
# Construct arrays with the dimensions for the 16 bars.
dx = dy = 0.5 * np.ones_like(zpos)
dz = hist.ravel()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='average')
plt.show()
# %%
# .. tags::
# plot-type: 3D, plot-type: histogram,
# level: beginner
| stable__gallery__mplot3d__hist3d | 0 | figure_000.png | Create 3D histogram of 2D data — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/hist3d.html#sphx-glr-download-gallery-mplot3d-hist3d-py | https://matplotlib.org/stable/_downloads/1c178669fa7845fc12cb2b519ae951fd/hist3d.py | hist3d.py | mplot3d | ok | 1 | null | |
"""
===============
2D images in 3D
===============
This example demonstrates how to plot 2D color coded images (similar to
`.Axes.imshow`) as a plane in 3D.
Matplotlib does not have a native function for this. Below we build one by relying
on `.Axes3D.plot_surface`. For simplicity, there are some differences to
`.Axes.imshow`: This function does not set the aspect of the Axes, hence pixels are
not necessarily square. Also, pixel edges are on integer values rather than pixel
centers. Furthermore, many optional parameters of `.Axes.imshow` are not implemented.
Multiple calls of ``imshow3d`` use independent norms and thus different color scales
by default. If you want to have a single common color scale, you need to construct
a suitable norm beforehand and pass it to all ``imshow3d`` calls.
A fundamental limitation of the 3D plotting engine is that intersecting objects cannot
be drawn correctly. One object will always be drawn after the other. Therefore,
multiple image planes can well be used in the background as shown in this example.
But this approach is not suitable if the planes intersect.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import Normalize
def imshow3d(ax, array, value_direction='z', pos=0, norm=None, cmap=None):
"""
Display a 2D array as a color-coded 2D image embedded in 3d.
The image will be in a plane perpendicular to the coordinate axis *value_direction*.
Parameters
----------
ax : Axes3D
The 3D Axes to plot into.
array : 2D numpy array
The image values.
value_direction : {'x', 'y', 'z'}
The axis normal to the image plane.
pos : float
The numeric value on the *value_direction* axis at which the image plane is
located.
norm : `~matplotlib.colors.Normalize`, default: Normalize
The normalization method used to scale scalar data. See `imshow()`.
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
The Colormap instance or registered colormap name used to map scalar data
to colors.
"""
if norm is None:
norm = Normalize()
colors = plt.get_cmap(cmap)(norm(array))
if value_direction == 'x':
nz, ny = array.shape
zi, yi = np.mgrid[0:nz + 1, 0:ny + 1]
xi = np.full_like(yi, pos)
elif value_direction == 'y':
nx, nz = array.shape
xi, zi = np.mgrid[0:nx + 1, 0:nz + 1]
yi = np.full_like(zi, pos)
elif value_direction == 'z':
ny, nx = array.shape
yi, xi = np.mgrid[0:ny + 1, 0:nx + 1]
zi = np.full_like(xi, pos)
else:
raise ValueError(f"Invalid value_direction: {value_direction!r}")
ax.plot_surface(xi, yi, zi, rstride=1, cstride=1, facecolors=colors, shade=False)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set(xlabel="x", ylabel="y", zlabel="z")
nx, ny, nz = 8, 10, 5
data_xy = np.arange(ny * nx).reshape(ny, nx) + 15 * np.random.random((ny, nx))
data_yz = np.arange(nz * ny).reshape(nz, ny) + 10 * np.random.random((nz, ny))
data_zx = np.arange(nx * nz).reshape(nx, nz) + 8 * np.random.random((nx, nz))
imshow3d(ax, data_xy)
imshow3d(ax, data_yz, value_direction='x', cmap='magma')
imshow3d(ax, data_zx, value_direction='y', pos=ny, cmap='plasma')
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# styling: colormap,
# level: advanced
| stable__gallery__mplot3d__imshow3d | 0 | figure_000.png | 2D images in 3D — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/imshow3d.html#sphx-glr-download-gallery-mplot3d-imshow3d-py | https://matplotlib.org/stable/_downloads/85c98843408756006b0ab8798a3b9590/imshow3d.py | imshow3d.py | mplot3d | ok | 1 | null | |
"""
===================
Intersecting planes
===================
This examples demonstrates drawing intersecting planes in 3D. It is a generalization
of :doc:`/gallery/mplot3d/imshow3d`.
Drawing intersecting planes in `.mplot3d` is complicated, because `.mplot3d` is not a
real 3D renderer, but only projects the Artists into 3D and draws them in the right
order. This does not work correctly if Artists overlap each other mutually. In this
example, we lift the problem of mutual overlap by segmenting the planes at their
intersections, making four parts out of each plane.
This examples only works correctly for planes that cut each other in haves. This
limitation is intentional to keep the code more readable. Cutting at arbitrary
positions would of course be possible but makes the code even more complex.
Thus, this example is more a demonstration of the concept how to work around
limitations of the 3D visualization, it's not a refined solution for drawing
arbitrary intersecting planes, which you can copy-and-paste as is.
"""
import matplotlib.pyplot as plt
import numpy as np
def plot_quadrants(ax, array, fixed_coord, cmap):
"""For a given 3d *array* plot a plane with *fixed_coord*, using four quadrants."""
nx, ny, nz = array.shape
index = {
'x': (nx // 2, slice(None), slice(None)),
'y': (slice(None), ny // 2, slice(None)),
'z': (slice(None), slice(None), nz // 2),
}[fixed_coord]
plane_data = array[index]
n0, n1 = plane_data.shape
quadrants = [
plane_data[:n0 // 2, :n1 // 2],
plane_data[:n0 // 2, n1 // 2:],
plane_data[n0 // 2:, :n1 // 2],
plane_data[n0 // 2:, n1 // 2:]
]
min_val = array.min()
max_val = array.max()
cmap = plt.get_cmap(cmap)
for i, quadrant in enumerate(quadrants):
facecolors = cmap((quadrant - min_val) / (max_val - min_val))
if fixed_coord == 'x':
Y, Z = np.mgrid[0:ny // 2, 0:nz // 2]
X = nx // 2 * np.ones_like(Y)
Y_offset = (i // 2) * ny // 2
Z_offset = (i % 2) * nz // 2
ax.plot_surface(X, Y + Y_offset, Z + Z_offset, rstride=1, cstride=1,
facecolors=facecolors, shade=False)
elif fixed_coord == 'y':
X, Z = np.mgrid[0:nx // 2, 0:nz // 2]
Y = ny // 2 * np.ones_like(X)
X_offset = (i // 2) * nx // 2
Z_offset = (i % 2) * nz // 2
ax.plot_surface(X + X_offset, Y, Z + Z_offset, rstride=1, cstride=1,
facecolors=facecolors, shade=False)
elif fixed_coord == 'z':
X, Y = np.mgrid[0:nx // 2, 0:ny // 2]
Z = nz // 2 * np.ones_like(X)
X_offset = (i // 2) * nx // 2
Y_offset = (i % 2) * ny // 2
ax.plot_surface(X + X_offset, Y + Y_offset, Z, rstride=1, cstride=1,
facecolors=facecolors, shade=False)
def figure_3D_array_slices(array, cmap=None):
"""Plot a 3d array using three intersecting centered planes."""
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set_box_aspect(array.shape)
plot_quadrants(ax, array, 'x', cmap=cmap)
plot_quadrants(ax, array, 'y', cmap=cmap)
plot_quadrants(ax, array, 'z', cmap=cmap)
return fig, ax
nx, ny, nz = 70, 100, 50
r_square = (np.mgrid[-1:1:1j * nx, -1:1:1j * ny, -1:1:1j * nz] ** 2).sum(0)
figure_3D_array_slices(r_square, cmap='viridis_r')
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: advanced
| stable__gallery__mplot3d__intersecting_planes | 0 | figure_000.png | Intersecting planes — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/intersecting_planes.html#sphx-glr-download-gallery-mplot3d-intersecting-planes-py | https://matplotlib.org/stable/_downloads/68e888ee31fb17abb06115e5c35bf104/intersecting_planes.py | intersecting_planes.py | mplot3d | ok | 1 | null | |
"""
================
Parametric curve
================
This example demonstrates plotting a parametric curve in 3D.
"""
import matplotlib.pyplot as plt
import numpy as np
ax = plt.figure().add_subplot(projection='3d')
# Prepare arrays x, y, z
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: beginner
| stable__gallery__mplot3d__lines3d | 0 | figure_000.png | Parametric curve — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/lines3d.html#sphx-glr-download-gallery-mplot3d-lines3d-py | https://matplotlib.org/stable/_downloads/7ae7882b92eea4ad03cff7c603d2a6dd/lines3d.py | lines3d.py | mplot3d | ok | 1 | null | |
"""
================
Lorenz attractor
================
This is an example of plotting Edward Lorenz's 1963 `"Deterministic Nonperiodic
Flow"`_ in a 3-dimensional space using mplot3d.
.. _"Deterministic Nonperiodic Flow":
https://journals.ametsoc.org/view/journals/atsc/20/2/1520-0469_1963_020_0130_dnf_2_0_co_2.xml
.. note::
Because this is a simple non-linear ODE, it would be more easily done using
SciPy's ODE solver, but this approach depends only upon NumPy.
"""
import matplotlib.pyplot as plt
import numpy as np
def lorenz(xyz, *, s=10, r=28, b=2.667):
"""
Parameters
----------
xyz : array-like, shape (3,)
Point of interest in three-dimensional space.
s, r, b : float
Parameters defining the Lorenz attractor.
Returns
-------
xyz_dot : array, shape (3,)
Values of the Lorenz attractor's partial derivatives at *xyz*.
"""
x, y, z = xyz
x_dot = s*(y - x)
y_dot = r*x - y - x*z
z_dot = x*y - b*z
return np.array([x_dot, y_dot, z_dot])
dt = 0.01
num_steps = 10000
xyzs = np.empty((num_steps + 1, 3)) # Need one more for the initial values
xyzs[0] = (0., 1., 1.05) # Set initial values
# Step through "time", calculating the partial derivatives at the current point
# and using them to estimate the next point
for i in range(num_steps):
xyzs[i + 1] = xyzs[i] + lorenz(xyzs[i]) * dt
# Plot
ax = plt.figure().add_subplot(projection='3d')
ax.plot(*xyzs.T, lw=0.5)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("Lorenz Attractor")
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: intermediate
| stable__gallery__mplot3d__lorenz_attractor | 0 | figure_000.png | Lorenz attractor — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/lorenz_attractor.html#sphx-glr-download-gallery-mplot3d-lorenz-attractor-py | https://matplotlib.org/stable/_downloads/7bcb50501dff2222c41e6dd71664c10f/lorenz_attractor.py | lorenz_attractor.py | mplot3d | ok | 1 | null | |
"""
=============================
2D and 3D Axes in same figure
=============================
This example shows a how to plot a 2D and a 3D plot on the same figure.
"""
import matplotlib.pyplot as plt
import numpy as np
def f(t):
return np.cos(2*np.pi*t) * np.exp(-t)
# Set up a figure twice as tall as it is wide
fig = plt.figure(figsize=plt.figaspect(2.))
fig.suptitle('A tale of 2 subplots')
# First subplot
ax = fig.add_subplot(2, 1, 1)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
t3 = np.arange(0.0, 2.0, 0.01)
ax.plot(t1, f(t1), 'bo',
t2, f(t2), 'k--', markerfacecolor='green')
ax.grid(True)
ax.set_ylabel('Damped oscillation')
# Second subplot
ax = fig.add_subplot(2, 1, 2, projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
linewidth=0, antialiased=False)
ax.set_zlim(-1, 1)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# component: subplot,
# level: beginner
| stable__gallery__mplot3d__mixed_subplots | 0 | figure_000.png | 2D and 3D Axes in same figure — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/mixed_subplots.html#sphx-glr-download-gallery-mplot3d-mixed-subplots-py | https://matplotlib.org/stable/_downloads/d97169a8850133651928362d22fa2ffb/mixed_subplots.py | mixed_subplots.py | mplot3d | ok | 1 | null | |
"""
=========================
Automatic text offsetting
=========================
This example demonstrates mplot3d's offset text display.
As one rotates the 3D figure, the offsets should remain oriented the
same way as the axis label, and should also be located "away"
from the center of the plot.
This demo triggers the display of the offset text for the x- and
y-axis by adding 1e5 to X and Y. Anything less would not
automatically trigger it.
"""
import matplotlib.pyplot as plt
import numpy as np
ax = plt.figure().add_subplot(projection='3d')
X, Y = np.mgrid[0:6*np.pi:0.25, 0:4*np.pi:0.25]
Z = np.sqrt(np.abs(np.cos(X) + np.cos(Y)))
ax.plot_surface(X + 1e5, Y + 1e5, Z, cmap='autumn', cstride=2, rstride=2)
ax.set_xlabel("X label")
ax.set_ylabel("Y label")
ax.set_zlabel("Z label")
ax.set_zlim(0, 2)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# component: label,
# interactivity: pan,
# level: beginner
| stable__gallery__mplot3d__offset | 0 | figure_000.png | Automatic text offsetting — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/offset.html#sphx-glr-download-gallery-mplot3d-offset-py | https://matplotlib.org/stable/_downloads/83a4da0793b08ae8f45786e3c9b4e373/offset.py | offset.py | mplot3d | ok | 1 | null | |
"""
============================
Draw flat objects in 3D plot
============================
Demonstrate using `.pathpatch_2d_to_3d` to 'draw' shapes and text on a 3D plot.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle, PathPatch
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D
import mpl_toolkits.mplot3d.art3d as art3d
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
"""
Plots the string *s* on the Axes *ax*, with position *xyz*, size *size*,
and rotation angle *angle*. *zdir* gives the axis which is to be treated as
the third dimension. *usetex* is a boolean indicating whether the string
should be run through a LaTeX subprocess or not. Any additional keyword
arguments are forwarded to `.transform_path`.
Note: zdir affects the interpretation of xyz.
"""
x, y, z = xyz
if zdir == "y":
xy1, z1 = (x, z), y
elif zdir == "x":
xy1, z1 = (y, z), x
else:
xy1, z1 = (x, y), z
text_path = TextPath((0, 0), s, size=size, usetex=usetex)
trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])
p1 = PathPatch(trans.transform_path(text_path), **kwargs)
ax.add_patch(p1)
art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
# Draw a circle on the x=0 'wall'
p = Circle((5, 5), 3)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")
# Manually label the axes
text3d(ax, (4, -2, 0), "X-axis", zdir="z", size=.5, usetex=False,
ec="none", fc="k")
text3d(ax, (12, 4, 0), "Y-axis", zdir="z", size=.5, usetex=False,
angle=np.pi / 2, ec="none", fc="k")
text3d(ax, (12, 10, 4), "Z-axis", zdir="y", size=.5, usetex=False,
angle=np.pi / 2, ec="none", fc="k")
# Write a Latex formula on the z=0 'floor'
text3d(ax, (1, 5, 0),
r"$\displaystyle G_{\mu\nu} + \Lambda g_{\mu\nu} = "
r"\frac{8\pi G}{c^4} T_{\mu\nu} $",
zdir="z", size=1, usetex=True,
ec="none", fc="k")
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# component: label,
# level: advanced
| stable__gallery__mplot3d__pathpatch3d | 0 | figure_000.png | Draw flat objects in 3D plot — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/pathpatch3d.html#sphx-glr-download-gallery-mplot3d-pathpatch3d-py | https://matplotlib.org/stable/_downloads/ab0fba45e231f940e29a0a3aacac8776/pathpatch3d.py | pathpatch3d.py | mplot3d | ok | 1 | null | |
"""
====================
Generate 3D polygons
====================
Demonstrate how to create polygons in 3D. Here we stack 3 hexagons.
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
# Coordinates of a hexagon
angles = np.linspace(0, 2 * np.pi, 6, endpoint=False)
x = np.cos(angles)
y = np.sin(angles)
zs = [-3, -2, -1]
# Close the hexagon by repeating the first vertex
x = np.append(x, x[0])
y = np.append(y, y[0])
verts = []
for z in zs:
verts.append(list(zip(x*z, y*z, np.full_like(x, z))))
verts = np.array(verts)
ax = plt.figure().add_subplot(projection='3d')
poly = Poly3DCollection(verts, alpha=.7)
ax.add_collection3d(poly)
ax.set_aspect('equalxy')
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# styling: colormap,
# level: intermediate
| stable__gallery__mplot3d__polys3d | 0 | figure_000.png | Generate 3D polygons — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/polys3d.html#sphx-glr-download-gallery-mplot3d-polys3d-py | https://matplotlib.org/stable/_downloads/54fadf20e54a727a7a5d9dd83e7a9e3b/polys3d.py | polys3d.py | mplot3d | ok | 1 | null | |
"""
========================
3D plot projection types
========================
Demonstrates the different camera projections for 3D plots, and the effects of
changing the focal length for a perspective projection. Note that Matplotlib
corrects for the 'zoom' effect of changing the focal length.
The default focal length of 1 corresponds to a Field of View (FOV) of 90 deg.
An increased focal length between 1 and infinity "flattens" the image, while a
decreased focal length between 1 and 0 exaggerates the perspective and gives
the image more apparent depth. In the limiting case, a focal length of
infinity corresponds to an orthographic projection after correction of the
zoom effect.
You can calculate focal length from a FOV via the equation:
.. math::
1 / \\tan (\\mathrm{FOV} / 2)
Or vice versa:
.. math::
\\mathrm{FOV} = 2 \\arctan (1 / \\mathrm{focal length})
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
fig, axs = plt.subplots(1, 3, subplot_kw={'projection': '3d'})
# Get the test data
X, Y, Z = axes3d.get_test_data(0.05)
# Plot the data
for ax in axs:
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
# Set the orthographic projection.
axs[0].set_proj_type('ortho') # FOV = 0 deg
axs[0].set_title("'ortho'\nfocal_length = ∞", fontsize=10)
# Set the perspective projections
axs[1].set_proj_type('persp') # FOV = 90 deg
axs[1].set_title("'persp'\nfocal_length = 1 (default)", fontsize=10)
axs[2].set_proj_type('persp', focal_length=0.2) # FOV = 157.4 deg
axs[2].set_title("'persp'\nfocal_length = 0.2", fontsize=10)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# styling: small-multiples,
# component: subplot,
# level: intermediate
| stable__gallery__mplot3d__projections | 0 | figure_000.png | 3D plot projection types — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/projections.html#sphx-glr-download-gallery-mplot3d-projections-py | https://matplotlib.org/stable/_downloads/9b22f16328066c6a0d023743cb5c6241/projections.py | projections.py | mplot3d | ok | 1 | null | |
"""
==============
3D quiver plot
==============
Demonstrates plotting directional arrows at points on a 3D meshgrid.
"""
import matplotlib.pyplot as plt
import numpy as np
ax = plt.figure().add_subplot(projection='3d')
# Make the grid
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
np.arange(-0.8, 1, 0.2),
np.arange(-0.8, 1, 0.8))
# Make the direction data for the arrows
u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
np.sin(np.pi * z))
ax.quiver(x, y, z, u, v, w, length=0.1, normalize=True)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# level: beginner
| stable__gallery__mplot3d__quiver3d | 0 | figure_000.png | 3D quiver plot — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/quiver3d.html#sphx-glr-download-gallery-mplot3d-quiver3d-py | https://matplotlib.org/stable/_downloads/19a0072d80eefa5dc179a38243c1da91/quiver3d.py | quiver3d.py | mplot3d | ok | 1 | null | |
"""
==============
3D scatterplot
==============
Demonstration of a basic scatterplot in 3D.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
def randrange(n, vmin, vmax):
"""
Helper function to make an array of random numbers having shape (n, )
with each number distributed Uniform(vmin, vmax).
"""
return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
n = 100
# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zlow, zhigh)
ax.scatter(xs, ys, zs, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
# %%
# .. tags::
# plot-type: 3D, plot-type: scatter,
# level: beginner
| stable__gallery__mplot3d__scatter3d | 0 | figure_000.png | 3D scatterplot — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/scatter3d.html#sphx-glr-download-gallery-mplot3d-scatter3d-py | https://matplotlib.org/stable/_downloads/faa507e7c87c72109d38e6eaffdc42e0/scatter3d.py | scatter3d.py | mplot3d | ok | 1 | null | |
"""
=======
3D stem
=======
Demonstration of a stem plot in 3D, which plots vertical lines from a baseline
to the *z*-coordinate and places a marker at the tip.
"""
import matplotlib.pyplot as plt
import numpy as np
theta = np.linspace(0, 2*np.pi)
x = np.cos(theta - np.pi/2)
y = np.sin(theta - np.pi/2)
z = theta
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
ax.stem(x, y, z)
plt.show()
# %%
#
# The position of the baseline can be adapted using *bottom*. The parameters
# *linefmt*, *markerfmt*, and *basefmt* control basic format properties of the
# plot. However, in contrast to `~.axes3d.Axes3D.plot` not all properties are
# configurable via keyword arguments. For more advanced control adapt the line
# objects returned by `~mpl_toolkits.mplot3d.axes3d.Axes3D.stem`.
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
markerline, stemlines, baseline = ax.stem(
x, y, z, linefmt='grey', markerfmt='D', bottom=np.pi)
markerline.set_markerfacecolor('none')
plt.show()
# %%
#
# The orientation of the stems and baseline can be changed using *orientation*.
# This determines in which direction the stems are projected from the head
# points, towards the *bottom* baseline.
#
# For examples, by setting ``orientation='x'``, the stems are projected along
# the *x*-direction, and the baseline is in the *yz*-plane.
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
markerline, stemlines, baseline = ax.stem(x, y, z, bottom=-1, orientation='x')
ax.set(xlabel='x', ylabel='y', zlabel='z')
plt.show()
# %%
# .. tags::
# plot-type: 3D, plot-type: speciality,
# level: beginner
| stable__gallery__mplot3d__stem3d_demo | 0 | figure_000.png | 3D stem — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/stem3d_demo.html#sphx-glr-download-gallery-mplot3d-stem3d-demo-py | https://matplotlib.org/stable/_downloads/c0fc774cc7f31ac97da140bcecf8167e/stem3d_demo.py | stem3d_demo.py | mplot3d | ok | 3 | null | |
"""
====================
3D plots as subplots
====================
Demonstrate including 3D plots as subplots.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from mpl_toolkits.mplot3d.axes3d import get_test_data
# set up a figure twice as wide as it is tall
fig = plt.figure(figsize=plt.figaspect(0.5))
# =============
# First subplot
# =============
# set up the Axes for the first plot
ax = fig.add_subplot(1, 2, 1, projection='3d')
# plot a 3D surface like in the example mplot3d/surface3d_demo
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
fig.colorbar(surf, shrink=0.5, aspect=10)
# ==============
# Second subplot
# ==============
# set up the Axes for the second plot
ax = fig.add_subplot(1, 2, 2, projection='3d')
# plot a 3D wireframe like in the example mplot3d/wire3d_demo
X, Y, Z = get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()
# %%
# .. tags::
# plot-type: 3D,
# component: subplot,
# level: advanced
| stable__gallery__mplot3d__subplot3d | 0 | figure_000.png | 3D plots as subplots — Matplotlib 3.10.8 documentation | https://matplotlib.org/stable/gallery/mplot3d/subplot3d.html#sphx-glr-download-gallery-mplot3d-subplot3d-py | https://matplotlib.org/stable/_downloads/c4f54a042d9a81d3afae26490415434f/subplot3d.py | subplot3d.py | mplot3d | ok | 1 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.