hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
4b8aebcd790f47a98cbdf812adfc77d96a78aa20aa469e84aa9248ca3a637f7f
|
"""
=================
Fancytextbox Demo
=================
"""
import matplotlib.pyplot as plt
plt.text(0.6, 0.7, "eggs", size=50, rotation=30.,
ha="center", va="center",
bbox=dict(boxstyle="round",
ec=(1., 0.5, 0.5),
fc=(1., 0.8, 0.8),
)
)
plt.text(0.55, 0.6, "spam", size=50, rotation=-25.,
ha="right", va="top",
bbox=dict(boxstyle="square",
ec=(1., 0.5, 0.5),
fc=(1., 0.8, 0.8),
)
)
plt.show()
|
0f25ede21c14a30ca0b3997b41385bba983f4019a288dcdabf2d462ed8859521
|
"""
===============================
A mathtext image as numpy array
===============================
Make images from LaTeX strings.
"""
import matplotlib.mathtext as mathtext
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc('image', origin='upper')
parser = mathtext.MathTextParser("Bitmap")
parser.to_png('test2.png',
r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} '
r'y\right)\right]$', color='green', fontsize=14, dpi=100)
rgba1, depth1 = parser.to_rgba(
r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200)
rgba2, depth2 = parser.to_rgba(
r'some other string', color='red', fontsize=20, dpi=200)
fig = plt.figure()
fig.figimage(rgba1, 100, 100)
fig.figimage(rgba2, 100, 300)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.mathtext
matplotlib.mathtext.MathTextParser
matplotlib.mathtext.MathTextParser.to_png
matplotlib.mathtext.MathTextParser.to_rgba
matplotlib.figure.Figure.figimage
|
7f22d12232b76844b772b5cf47b0836db204147370b05707d5c766f5002c36cc
|
"""
===========
Usetex Demo
===========
Shows how to use latex in a plot.
Also refer to the :doc:`/tutorials/text/usetex` guide.
"""
import numpy as np
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
# interface tracking profiles
N = 500
delta = 0.6
X = np.linspace(-1, 1, N)
plt.plot(X, (1 - np.tanh(4 * X / delta)) / 2, # phase field tanh profiles
X, (1.4 + np.tanh(4 * X / delta)) / 4, "C2", # composition profile
X, X < 0, 'k--') # sharp interface
# legend
plt.legend(('phase field', 'level set', 'sharp interface'),
shadow=True, loc=(0.01, 0.48), handlelength=1.5, fontsize=16)
# the arrow
plt.annotate("", xy=(-delta / 2., 0.1), xytext=(delta / 2., 0.1),
arrowprops=dict(arrowstyle="<->", connectionstyle="arc3"))
plt.text(0, 0.1, r'$\delta$',
{'color': 'black', 'fontsize': 24, 'ha': 'center', 'va': 'center',
'bbox': dict(boxstyle="round", fc="white", ec="black", pad=0.2)})
# Use tex in labels
plt.xticks((-1, 0, 1), ('$-1$', r'$\pm 0$', '$+1$'), color='k', size=20)
# Left Y-axis labels, combine math mode and text mode
plt.ylabel(r'\bf{phase field} $\phi$', {'color': 'C0', 'fontsize': 20})
plt.yticks((0, 0.5, 1), (r'\bf{0}', r'\bf{.5}', r'\bf{1}'), color='k', size=20)
# Right Y-axis labels
plt.text(1.02, 0.5, r"\bf{level set} $\phi$", {'color': 'C2', 'fontsize': 20},
horizontalalignment='left',
verticalalignment='center',
rotation=90,
clip_on=False,
transform=plt.gca().transAxes)
# Use multiline environment inside a `text`.
# level set equations
eq1 = r"\begin{eqnarray*}" + \
r"|\nabla\phi| &=& 1,\\" + \
r"\frac{\partial \phi}{\partial t} + U|\nabla \phi| &=& 0 " + \
r"\end{eqnarray*}"
plt.text(1, 0.9, eq1, {'color': 'C2', 'fontsize': 18}, va="top", ha="right")
# phase field equations
eq2 = r'\begin{eqnarray*}' + \
r'\mathcal{F} &=& \int f\left( \phi, c \right) dV, \\ ' + \
r'\frac{ \partial \phi } { \partial t } &=& -M_{ \phi } ' + \
r'\frac{ \delta \mathcal{F} } { \delta \phi }' + \
r'\end{eqnarray*}'
plt.text(0.18, 0.18, eq2, {'color': 'C0', 'fontsize': 16})
plt.text(-1, .30, r'gamma: $\gamma$', {'color': 'r', 'fontsize': 20})
plt.text(-1, .18, r'Omega: $\Omega$', {'color': 'b', 'fontsize': 20})
plt.show()
|
3932d274776e3711b39a6ef8d20b230df8c4d4d82caeec0c1d69261821dc5b43
|
"""
==============================
Text Rotation Relative To Line
==============================
Text objects in matplotlib are normally rotated with respect to the
screen coordinate system (i.e., 45 degrees rotation plots text along a
line that is in between horizontal and vertical no matter how the axes
are changed). However, at times one wants to rotate text with respect
to something on the plot. In this case, the correct angle won't be
the angle of that object in the plot coordinate system, but the angle
that that object APPEARS in the screen coordinate system. This angle
is found by transforming the angle from the plot to the screen
coordinate system, as shown in the example below.
"""
import matplotlib.pyplot as plt
import numpy as np
# Plot diagonal line (45 degrees)
h = plt.plot(np.arange(0, 10), np.arange(0, 10))
# set limits so that it no longer looks on screen to be 45 degrees
plt.xlim([-10, 20])
# Locations to plot text
l1 = np.array((1, 1))
l2 = np.array((5, 5))
# Rotate angle
angle = 45
trans_angle = plt.gca().transData.transform_angles(np.array((45,)),
l2.reshape((1, 2)))[0]
# Plot text
th1 = plt.text(l1[0], l1[1], 'text not rotated correctly', fontsize=16,
rotation=angle, rotation_mode='anchor')
th2 = plt.text(l2[0], l2[1], 'text rotated correctly', fontsize=16,
rotation=trans_angle, rotation_mode='anchor')
plt.show()
|
7c4fa43c8336d81eb0ec93fab8d3647a4556b18f2a6830987d932e042f3858b7
|
"""
=================
Arrow Simple Demo
=================
"""
import matplotlib.pyplot as plt
ax = plt.axes()
ax.arrow(0, 0, 0.5, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')
plt.show()
|
ac085c6aa1e69a170b9e536a715e811cda0d828cde13377d28afbc070680493e
|
"""
==================
Usetex Fonteffects
==================
This script demonstrates that font effects specified in your pdftex.map
are now supported in pdf usetex.
"""
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('text', usetex=True)
def setfont(font):
return r'\font\a %s at 14pt\a ' % font
for y, font, text in zip(range(5),
['ptmr8r', 'ptmri8r', 'ptmro8r',
'ptmr8rn', 'ptmrr8re'],
['Nimbus Roman No9 L ' + x for x in
['', 'Italics (real italics for comparison)',
'(slanted)', '(condensed)', '(extended)']]):
plt.text(0, y, setfont(font) + text)
plt.ylim(-1, 5)
plt.xlim(-0.2, 0.6)
plt.setp(plt.gca(), frame_on=False, xticks=(), yticks=())
plt.title('Usetex font effects')
plt.savefig('usetex_fonteffects.pdf')
|
ea4633156ae2a224eb5dc9988fcf9ec551f714305d48fb12f57481af233116c1
|
"""
=============
Mathtext Demo
=============
Use Matplotlib's internal LaTeX parser and layout engine. For true LaTeX
rendering, see the text.usetex option.
"""
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], label=r'$\sqrt{x^2}$')
ax.legend()
ax.set_xlabel(r'$\Delta_i^j$', fontsize=20)
ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20)
ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} '
r'\Delta_{i+1}^j$', fontsize=20)
tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$'
ax.text(1, 1.6, tex, fontsize=20, va='bottom')
fig.tight_layout()
plt.show()
|
2a07e6305b2f2e8f6f7934ed2749e4a10305ad5fe51b6b207233fea338f474f9
|
"""
===============
STIX Fonts Demo
===============
Demonstration of `STIX Fonts <https://www.stixfonts.org/>`_ used in LaTeX
rendering.
"""
import matplotlib.pyplot as plt
circle123 = "\N{CIRCLED DIGIT ONE}\N{CIRCLED DIGIT TWO}\N{CIRCLED DIGIT THREE}"
tests = [
r'$%s\;\mathrm{%s}\;\mathbf{%s}$' % ((circle123,) * 3),
r'$\mathsf{Sans \Omega}\;\mathrm{\mathsf{Sans \Omega}}\;'
r'\mathbf{\mathsf{Sans \Omega}}$',
r'$\mathtt{Monospace}$',
r'$\mathcal{CALLIGRAPHIC}$',
r'$\mathbb{Blackboard\;\pi}$',
r'$\mathrm{\mathbb{Blackboard\;\pi}}$',
r'$\mathbf{\mathbb{Blackboard\;\pi}}$',
r'$\mathfrak{Fraktur}\;\mathbf{\mathfrak{Fraktur}}$',
r'$\mathscr{Script}$',
]
fig = plt.figure(figsize=(8, len(tests) + 2))
for i, s in enumerate(tests[::-1]):
fig.text(0, (i + .5) / len(tests), s, fontsize=32)
plt.show()
|
ce11415692a7ec9ea152b864849f472a1a1c603c748d06405e01230fbc97ad20
|
"""
==============
Text watermark
==============
A watermark effect can be achieved by drawing a semi-transparent text.
"""
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
ax.grid()
ax.text(0.5, 0.5, 'created with matplotlib', transform=ax.transAxes,
fontsize=40, color='gray', alpha=0.5,
ha='center', va='center', rotation='30')
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.figure.Figure.text
|
bed4aff2e9ae96376120c1a8d1365c9c80c4c7b6de4d95ea26aaf56eb2fae019
|
"""
================
Annotating Plots
================
The following examples show how it is possible to annotate plots in matplotlib.
This includes highlighting specific points of interest and using various
visual tools to call attention to this point. For a more complete and in-depth
description of the annotation and text tools in :mod:`matplotlib`, see the
:doc:`tutorial on annotation </tutorials/text/annotations>`.
"""
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import numpy as np
from matplotlib.text import OffsetFrom
###############################################################################
# Specifying text points and annotation points
# --------------------------------------------
#
# You must specify an annotation point `xy=(x,y)` to annotate this point.
# additionally, you may specify a text point `xytext=(x,y)` for the
# location of the text for this annotation. Optionally, you can
# specify the coordinate system of `xy` and `xytext` with one of the
# following strings for `xycoords` and `textcoords` (default is 'data')::
#
# 'figure points' : points from the lower left corner of the figure
# 'figure pixels' : pixels from the lower left corner of the figure
# 'figure fraction' : 0,0 is lower left of figure and 1,1 is upper, right
# 'axes points' : points from lower left corner of axes
# 'axes pixels' : pixels from lower left corner of axes
# 'axes fraction' : 0,0 is lower left of axes and 1,1 is upper right
# 'offset points' : Specify an offset (in points) from the xy value
# 'offset pixels' : Specify an offset (in pixels) from the xy value
# 'data' : use the axes data coordinate system
#
# Note: for physical coordinate systems (points or pixels) the origin is the
# (bottom, left) of the figure or axes.
#
# Optionally, you can specify arrow properties which draws and arrow
# from the text to the annotated point by giving a dictionary of arrow
# properties
#
# Valid keys are::
#
# width : the width of the arrow in points
# frac : the fraction of the arrow length occupied by the head
# headwidth : the width of the base of the arrow head in points
# shrink : move the tip and base some percent away from the
# annotated point and text
# any key for matplotlib.patches.polygon (e.g., facecolor)
# Create our figure and data we'll use for plotting
fig, ax = plt.subplots(figsize=(3, 3))
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
# Plot a line and add some simple annotations
line, = ax.plot(t, s)
ax.annotate('figure pixels',
xy=(10, 10), xycoords='figure pixels')
ax.annotate('figure points',
xy=(80, 80), xycoords='figure points')
ax.annotate('figure fraction',
xy=(.025, .975), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=20)
# The following examples show off how these arrows are drawn.
ax.annotate('point offset from data',
xy=(2, 1), xycoords='data',
xytext=(-15, 25), textcoords='offset points',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='right', verticalalignment='bottom')
ax.annotate('axes fraction',
xy=(3, 1), xycoords='data',
xytext=(0.8, 0.95), textcoords='axes fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='right', verticalalignment='top')
# You may also use negative points or pixels to specify from (right, top).
# E.g., (-10, 10) is 10 points to the left of the right side of the axes and 10
# points above the bottom
ax.annotate('pixel offset from axes fraction',
xy=(1, 0), xycoords='axes fraction',
xytext=(-20, 20), textcoords='offset pixels',
horizontalalignment='right',
verticalalignment='bottom')
ax.set(xlim=(-1, 5), ylim=(-3, 5))
###############################################################################
# Using multiple coordinate systems and axis types
# ------------------------------------------------
#
# You can specify the xypoint and the xytext in different positions and
# coordinate systems, and optionally turn on a connecting line and mark
# the point with a marker. Annotations work on polar axes too.
#
# In the example below, the xy point is in native coordinates (xycoords
# defaults to 'data'). For a polar axes, this is in (theta, radius) space.
# The text in the example is placed in the fractional figure coordinate system.
# Text keyword args like horizontal and vertical alignment are respected.
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'), figsize=(3, 3))
r = np.arange(0, 1, 0.001)
theta = 2*2*np.pi*r
line, = ax.plot(theta, r)
ind = 800
thisr, thistheta = r[ind], theta[ind]
ax.plot([thistheta], [thisr], 'o')
ax.annotate('a polar annotation',
xy=(thistheta, thisr), # theta, radius
xytext=(0.05, 0.05), # fraction, fraction
textcoords='figure fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='left',
verticalalignment='bottom')
# You can also use polar notation on a cartesian axes. Here the native
# coordinate system ('data') is cartesian, so you need to specify the
# xycoords and textcoords as 'polar' if you want to use (theta, radius).
el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)
fig, ax = plt.subplots(subplot_kw=dict(aspect='equal'))
ax.add_artist(el)
el.set_clip_box(ax.bbox)
ax.annotate('the top',
xy=(np.pi/2., 10.), # theta, radius
xytext=(np.pi/3, 20.), # theta, radius
xycoords='polar',
textcoords='polar',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='left',
verticalalignment='bottom',
clip_on=True) # clip to the axes bounding box
ax.set(xlim=[-20, 20], ylim=[-20, 20])
###############################################################################
# Customizing arrow and bubble styles
# -----------------------------------
#
# The arrow between xytext and the annotation point, as well as the bubble
# that covers the annotation text, are highly customizable. Below are a few
# parameter options as well as their resulting output.
fig, ax = plt.subplots(figsize=(8, 5))
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=3)
ax.annotate('straight',
xy=(0, 1), xycoords='data',
xytext=(-50, 30), textcoords='offset points',
arrowprops=dict(arrowstyle="->"))
ax.annotate('arc3,\nrad 0.2',
xy=(0.5, -1), xycoords='data',
xytext=(-80, -60), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3,rad=.2"))
ax.annotate('arc,\nangle 50',
xy=(1., 1), xycoords='data',
xytext=(-90, 50), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc,angleA=0,armA=50,rad=10"))
ax.annotate('arc,\narms',
xy=(1.5, -1), xycoords='data',
xytext=(-80, -60), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc,angleA=0,armA=40,angleB=-90,armB=30,rad=7"))
ax.annotate('angle,\nangle 90',
xy=(2., 1), xycoords='data',
xytext=(-70, 30), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=90,rad=10"))
ax.annotate('angle3,\nangle -90',
xy=(2.5, -1), xycoords='data',
xytext=(-80, -60), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3,angleA=0,angleB=-90"))
ax.annotate('angle,\nround',
xy=(3., 1), xycoords='data',
xytext=(-60, 30), textcoords='offset points',
bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=90,rad=10"))
ax.annotate('angle,\nround4',
xy=(3.5, -1), xycoords='data',
xytext=(-70, -80), textcoords='offset points',
size=20,
bbox=dict(boxstyle="round4,pad=.5", fc="0.8"),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=-90,rad=10"))
ax.annotate('angle,\nshrink',
xy=(4., 1), xycoords='data',
xytext=(-60, 30), textcoords='offset points',
bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="->",
shrinkA=0, shrinkB=10,
connectionstyle="angle,angleA=0,angleB=90,rad=10"))
# You can pass an empty string to get only annotation arrows rendered
ann = ax.annotate('', xy=(4., 1.), xycoords='data',
xytext=(4.5, -1), textcoords='data',
arrowprops=dict(arrowstyle="<->",
connectionstyle="bar",
ec="k",
shrinkA=5, shrinkB=5))
ax.set(xlim=(-1, 5), ylim=(-4, 3))
# We'll create another figure so that it doesn't get too cluttered
fig, ax = plt.subplots()
el = Ellipse((2, -1), 0.5, 0.5)
ax.add_patch(el)
ax.annotate('$->$',
xy=(2., -1), xycoords='data',
xytext=(-150, -140), textcoords='offset points',
bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="->",
patchB=el,
connectionstyle="angle,angleA=90,angleB=0,rad=10"))
ax.annotate('arrow\nfancy',
xy=(2., -1), xycoords='data',
xytext=(-100, 60), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="fancy",
fc="0.6", ec="none",
patchB=el,
connectionstyle="angle3,angleA=0,angleB=-90"))
ax.annotate('arrow\nsimple',
xy=(2., -1), xycoords='data',
xytext=(100, 60), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="simple",
fc="0.6", ec="none",
patchB=el,
connectionstyle="arc3,rad=0.3"))
ax.annotate('wedge',
xy=(2., -1), xycoords='data',
xytext=(-100, -100), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="wedge,tail_width=0.7",
fc="0.6", ec="none",
patchB=el,
connectionstyle="arc3,rad=-0.3"))
ann = ax.annotate('bubble,\ncontours',
xy=(2., -1), xycoords='data',
xytext=(0, -70), textcoords='offset points',
size=20,
bbox=dict(boxstyle="round",
fc=(1.0, 0.7, 0.7),
ec=(1., .5, .5)),
arrowprops=dict(arrowstyle="wedge,tail_width=1.",
fc=(1.0, 0.7, 0.7), ec=(1., .5, .5),
patchA=None,
patchB=el,
relpos=(0.2, 0.8),
connectionstyle="arc3,rad=-0.1"))
ann = ax.annotate('bubble',
xy=(2., -1), xycoords='data',
xytext=(55, 0), textcoords='offset points',
size=20, va="center",
bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"),
arrowprops=dict(arrowstyle="wedge,tail_width=1.",
fc=(1.0, 0.7, 0.7), ec="none",
patchA=None,
patchB=el,
relpos=(0.2, 0.5)))
ax.set(xlim=(-1, 5), ylim=(-5, 3))
###############################################################################
# More examples of coordinate systems
# -----------------------------------
#
# Below we'll show a few more examples of coordinate systems and how the
# location of annotations may be specified.
fig, (ax1, ax2) = plt.subplots(1, 2)
bbox_args = dict(boxstyle="round", fc="0.8")
arrow_args = dict(arrowstyle="->")
# Here we'll demonstrate the extents of the coordinate system and how
# we place annotating text.
ax1.annotate('figure fraction : 0, 0', xy=(0, 0), xycoords='figure fraction',
xytext=(20, 20), textcoords='offset points',
ha="left", va="bottom",
bbox=bbox_args,
arrowprops=arrow_args)
ax1.annotate('figure fraction : 1, 1', xy=(1, 1), xycoords='figure fraction',
xytext=(-20, -20), textcoords='offset points',
ha="right", va="top",
bbox=bbox_args,
arrowprops=arrow_args)
ax1.annotate('axes fraction : 0, 0', xy=(0, 0), xycoords='axes fraction',
xytext=(20, 20), textcoords='offset points',
ha="left", va="bottom",
bbox=bbox_args,
arrowprops=arrow_args)
ax1.annotate('axes fraction : 1, 1', xy=(1, 1), xycoords='axes fraction',
xytext=(-20, -20), textcoords='offset points',
ha="right", va="top",
bbox=bbox_args,
arrowprops=arrow_args)
# It is also possible to generate draggable annotations
an1 = ax1.annotate('Drag me 1', xy=(.5, .7), xycoords='data',
#xytext=(.5, .7), textcoords='data',
ha="center", va="center",
bbox=bbox_args,
#arrowprops=arrow_args
)
an2 = ax1.annotate('Drag me 2', xy=(.5, .5), xycoords=an1,
xytext=(.5, .3), textcoords='axes fraction',
ha="center", va="center",
bbox=bbox_args,
arrowprops=dict(patchB=an1.get_bbox_patch(),
connectionstyle="arc3,rad=0.2",
**arrow_args))
an1.draggable()
an2.draggable()
an3 = ax1.annotate('', xy=(.5, .5), xycoords=an2,
xytext=(.5, .5), textcoords=an1,
ha="center", va="center",
bbox=bbox_args,
arrowprops=dict(patchA=an1.get_bbox_patch(),
patchB=an2.get_bbox_patch(),
connectionstyle="arc3,rad=0.2",
**arrow_args))
# Finally we'll show off some more complex annotation and placement
text = ax2.annotate('xy=(0, 1)\nxycoords=("data", "axes fraction")',
xy=(0, 1), xycoords=("data", 'axes fraction'),
xytext=(0, -20), textcoords='offset points',
ha="center", va="top",
bbox=bbox_args,
arrowprops=arrow_args)
ax2.annotate('xy=(0.5, 0)\nxycoords=artist',
xy=(0.5, 0.), xycoords=text,
xytext=(0, -20), textcoords='offset points',
ha="center", va="top",
bbox=bbox_args,
arrowprops=arrow_args)
ax2.annotate('xy=(0.8, 0.5)\nxycoords=ax1.transData',
xy=(0.8, 0.5), xycoords=ax1.transData,
xytext=(10, 10),
textcoords=OffsetFrom(ax2.bbox, (0, 0), "points"),
ha="left", va="bottom",
bbox=bbox_args,
arrowprops=arrow_args)
ax2.set(xlim=[-2, 2], ylim=[-2, 2])
plt.show()
|
f3cd7145ecaadc6bbab5b64999397793d901dd3c906032a3cfc9d1043542151f
|
'''
=========================================
Labeling ticks using engineering notation
=========================================
Use of the engineering Formatter.
'''
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import EngFormatter
# Fixing random state for reproducibility
prng = np.random.RandomState(19680801)
# Create artificial data to plot.
# The x data span over several decades to demonstrate several SI prefixes.
xs = np.logspace(1, 9, 100)
ys = (0.8 + 0.4 * prng.uniform(size=100)) * np.log10(xs)**2
# Figure width is doubled (2*6.4) to display nicely 2 subplots side by side.
fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(7, 9.6))
for ax in (ax0, ax1):
ax.set_xscale('log')
# Demo of the default settings, with a user-defined unit label.
ax0.set_title('Full unit ticklabels, w/ default precision & space separator')
formatter0 = EngFormatter(unit='Hz')
ax0.xaxis.set_major_formatter(formatter0)
ax0.plot(xs, ys)
ax0.set_xlabel('Frequency')
# Demo of the options `places` (number of digit after decimal point) and
# `sep` (separator between the number and the prefix/unit).
ax1.set_title('SI-prefix only ticklabels, 1-digit precision & '
'thin space separator')
formatter1 = EngFormatter(places=1, sep="\N{THIN SPACE}") # U+2009
ax1.xaxis.set_major_formatter(formatter1)
ax1.plot(xs, ys)
ax1.set_xlabel('Frequency [Hz]')
plt.tight_layout()
plt.show()
|
83883f0d931da80b9a0a15bea01d964fd2b43b440b81342d85eeec4429069d3c
|
"""
=================
Mathtext Examples
=================
Selected features of Matplotlib's math rendering engine.
"""
import matplotlib.pyplot as plt
import subprocess
import sys
import re
# Selection of features following "Writing mathematical expressions" tutorial
mathtext_titles = {
0: "Header demo",
1: "Subscripts and superscripts",
2: "Fractions, binomials and stacked numbers",
3: "Radicals",
4: "Fonts",
5: "Accents",
6: "Greek, Hebrew",
7: "Delimiters, functions and Symbols"}
n_lines = len(mathtext_titles)
# Randomly picked examples
mathext_demos = {
0: r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = "
r"U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} "
r"\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ "
r"U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_"
r"{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$",
1: r"$\alpha_i > \beta_i,\ "
r"\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ "
r"\ldots$",
2: r"$\frac{3}{4},\ \binom{3}{4},\ \genfrac{}{}{0}{}{3}{4},\ "
r"\left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$",
3: r"$\sqrt{2},\ \sqrt[3]{x},\ \ldots$",
4: r"$\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ "
r"\mathrm{or}\ \mathcal{CALLIGRAPHY}$",
5: r"$\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ "
r"\hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ "
r"\ldots$",
6: r"$\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ "
r"\Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ "
r"\aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$",
7: r"$\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ "
r"\log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ "
r"\infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$"}
def doall():
# Colors used in mpl online documentation.
mpl_blue_rvb = (191. / 255., 209. / 256., 212. / 255.)
mpl_orange_rvb = (202. / 255., 121. / 256., 0. / 255.)
mpl_grey_rvb = (51. / 255., 51. / 255., 51. / 255.)
# Creating figure and axis.
plt.figure(figsize=(6, 7))
plt.axes([0.01, 0.01, 0.98, 0.90], facecolor="white", frameon=True)
plt.gca().set_xlim(0., 1.)
plt.gca().set_ylim(0., 1.)
plt.gca().set_title("Matplotlib's math rendering engine",
color=mpl_grey_rvb, fontsize=14, weight='bold')
plt.gca().set_xticklabels("", visible=False)
plt.gca().set_yticklabels("", visible=False)
# Gap between lines in axes coords
line_axesfrac = (1. / (n_lines))
# Plotting header demonstration formula
full_demo = mathext_demos[0]
plt.annotate(full_demo,
xy=(0.5, 1. - 0.59 * line_axesfrac),
color=mpl_orange_rvb, ha='center', fontsize=20)
# Plotting features demonstration formulae
for i_line in range(1, n_lines):
baseline = 1 - (i_line) * line_axesfrac
baseline_next = baseline - line_axesfrac
title = mathtext_titles[i_line] + ":"
fill_color = ['white', mpl_blue_rvb][i_line % 2]
plt.fill_between([0., 1.], [baseline, baseline],
[baseline_next, baseline_next],
color=fill_color, alpha=0.5)
plt.annotate(title,
xy=(0.07, baseline - 0.3 * line_axesfrac),
color=mpl_grey_rvb, weight='bold')
demo = mathext_demos[i_line]
plt.annotate(demo,
xy=(0.05, baseline - 0.75 * line_axesfrac),
color=mpl_grey_rvb, fontsize=16)
for i in range(n_lines):
s = mathext_demos[i]
print(i, s)
plt.show()
if '--latex' in sys.argv:
# Run: python mathtext_examples.py --latex
# Need amsmath and amssymb packages.
fd = open("mathtext_examples.ltx", "w")
fd.write("\\documentclass{article}\n")
fd.write("\\usepackage{amsmath, amssymb}\n")
fd.write("\\begin{document}\n")
fd.write("\\begin{enumerate}\n")
for i in range(n_lines):
s = mathext_demos[i]
s = re.sub(r"(?<!\\)\$", "$$", s)
fd.write("\\item %s\n" % s)
fd.write("\\end{enumerate}\n")
fd.write("\\end{document}\n")
fd.close()
subprocess.call(["pdflatex", "mathtext_examples.ltx"])
else:
doall()
|
d945745e6494de0fd36625ea2a1029e72b6bc22cdf38692087aa00a98f2dba6c
|
r"""
=======================
Demo Text Rotation Mode
=======================
This example illustrates the effect of ``rotation_mode`` on the positioning
of rotated text.
Rotated `.Text`\s are created by passing the parameter ``rotation`` to
the constructor or the axes' method `~.axes.Axes.text`.
The actual positioning depends on the additional parameters
``horizontalalignment``, ``verticalalignment`` and ``rotation_mode``.
``rotation_mode`` determines the order of rotation and alignment:
- ``roation_mode='default'`` (or None) first rotates the text and then aligns
the bounding box of the rotated text.
- ``roation_mode='anchor'`` aligns the unrotated text and then rotates the
text around the point of alignment.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_grid import ImageGrid
def test_rotation_mode(fig, mode, subplot_location):
ha_list = ["left", "center", "right"]
va_list = ["top", "center", "baseline", "bottom"]
grid = ImageGrid(fig, subplot_location,
nrows_ncols=(len(va_list), len(ha_list)),
share_all=True, aspect=True, cbar_mode=None)
# labels and title
for ha, ax in zip(ha_list, grid.axes_row[-1]):
ax.axis["bottom"].label.set_text(ha)
for va, ax in zip(va_list, grid.axes_column[0]):
ax.axis["left"].label.set_text(va)
grid.axes_row[0][1].set_title(f"rotation_mode='{mode}'", size="large")
if mode == "default":
kw = dict()
else:
kw = dict(
bbox=dict(boxstyle="square,pad=0.", ec="none", fc="C1", alpha=0.3))
# use a different text alignment in each axes
texts = []
for (va, ha), ax in zip([(x, y) for x in va_list for y in ha_list], grid):
# prepare axes layout
for axis in ax.axis.values():
axis.toggle(ticks=False, ticklabels=False)
ax.axis([0, 1, 0, 1])
ax.axvline(0.5, color="skyblue", zorder=0)
ax.axhline(0.5, color="skyblue", zorder=0)
ax.plot(0.5, 0.5, color="C0", marker="o", zorder=1)
# add text with rotation and alignment settings
tx = ax.text(0.5, 0.5, "Tpg",
size="x-large", rotation=40,
horizontalalignment=ha, verticalalignment=va,
rotation_mode=mode, **kw)
texts.append(tx)
if mode == "default":
# highlight bbox
fig.canvas.draw()
for ax, tx in zip(grid, texts):
bb = tx.get_window_extent().inverse_transformed(ax.transData)
rect = plt.Rectangle((bb.x0, bb.y0), bb.width, bb.height,
facecolor="C1", alpha=0.3, zorder=2)
ax.add_patch(rect)
fig = plt.figure(figsize=(8, 6))
test_rotation_mode(fig, "default", 121)
test_rotation_mode(fig, "anchor", 122)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following method is shown in this example:
import matplotlib
matplotlib.axes.Axes.text
|
ecc829c38c3ff28ce5fb6f0094cf439628d09da0e78f0f02fead4b7610465d3e
|
"""
=====================================
Custom tick formatter for time series
=====================================
When plotting time series, e.g., financial time series, one often wants
to leave out days on which there is no data, i.e. weekends. The example
below shows how to use an 'index formatter' to achieve the desired plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
# Load a numpy record array from yahoo csv data with fields date, open, close,
# volume, adj_close from the mpl-data/example directory. The record array
# stores the date as an np.datetime64 with a day unit ('D') in the date column.
with cbook.get_sample_data('goog.npz') as datafile:
r = np.load(datafile)['price_data'].view(np.recarray)
r = r[-30:] # get the last 30 days
# Matplotlib works better with datetime.datetime than np.datetime64, but the
# latter is more portable.
date = r.date.astype('O')
# first we'll do it the default way, with gaps on weekends
fig, axes = plt.subplots(ncols=2, figsize=(8, 4))
ax = axes[0]
ax.plot(date, r.adj_close, 'o-')
ax.set_title("Default")
fig.autofmt_xdate()
# next we'll write a custom formatter
N = len(r)
ind = np.arange(N) # the evenly spaced plot indices
def format_date(x, pos=None):
thisind = np.clip(int(x + 0.5), 0, N - 1)
return date[thisind].strftime('%Y-%m-%d')
ax = axes[1]
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
ax.set_title("Custom tick formatter")
fig.autofmt_xdate()
plt.show()
|
ba23102135e501100c0e301327d017f6cad7e175e203643f298ab8c760bdc332
|
"""
==================
Figure legend demo
==================
Instead of plotting a legend on each axis, a legend for all the artists on all
the sub-axes of a figure can be plotted instead.
"""
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2)
x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2 * np.pi * x)
y2 = np.exp(-x)
l1, = axs[0].plot(x, y1)
l2, = axs[0].plot(x, y2, marker='o')
y3 = np.sin(4 * np.pi * x)
y4 = np.exp(-2 * x)
l3, = axs[1].plot(x, y3, color='tab:green')
l4, = axs[1].plot(x, y4, color='tab:red', marker='^')
fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left')
fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right')
plt.tight_layout()
plt.show()
|
2b68523645f6388a1cfb91805fb242aa3a1423416df51deb2987063ea716c299
|
"""
==============
Demo Text Path
==============
Use a text as `Path`. The tool that allows for such conversion is a
`~matplotlib.textpath.TextPath`. The resulting path can be employed
e.g. as a clip path for an image.
"""
import matplotlib.pyplot as plt
from matplotlib.image import BboxImage
import numpy as np
from matplotlib.transforms import IdentityTransform
import matplotlib.patches as mpatches
from matplotlib.offsetbox import AnnotationBbox,\
AnchoredOffsetbox, AuxTransformBox
from matplotlib.cbook import get_sample_data
from matplotlib.text import TextPath
class PathClippedImagePatch(mpatches.PathPatch):
"""
The given image is used to draw the face of the patch. Internally,
it uses BboxImage whose clippath set to the path of the patch.
FIXME : The result is currently dpi dependent.
"""
def __init__(self, path, bbox_image, **kwargs):
mpatches.PathPatch.__init__(self, path, **kwargs)
self._init_bbox_image(bbox_image)
def set_facecolor(self, color):
"""simply ignore facecolor"""
mpatches.PathPatch.set_facecolor(self, "none")
def _init_bbox_image(self, im):
bbox_image = BboxImage(self.get_window_extent,
norm=None,
origin=None,
)
bbox_image.set_transform(IdentityTransform())
bbox_image.set_data(im)
self.bbox_image = bbox_image
def draw(self, renderer=None):
# the clip path must be updated every draw. any solution? -JJ
self.bbox_image.set_clip_path(self._path, self.get_transform())
self.bbox_image.draw(renderer)
mpatches.PathPatch.draw(self, renderer)
if __name__ == "__main__":
usetex = plt.rcParams["text.usetex"]
fig = plt.figure()
# EXAMPLE 1
ax = plt.subplot(211)
arr = plt.imread(get_sample_data("grace_hopper.png"))
text_path = TextPath((0, 0), "!?", size=150)
p = PathClippedImagePatch(text_path, arr, ec="k",
transform=IdentityTransform())
# p.set_clip_on(False)
# make offset box
offsetbox = AuxTransformBox(IdentityTransform())
offsetbox.add_artist(p)
# make anchored offset box
ao = AnchoredOffsetbox(loc='upper left', child=offsetbox, frameon=True,
borderpad=0.2)
ax.add_artist(ao)
# another text
from matplotlib.patches import PathPatch
if usetex:
r = r"\mbox{textpath supports mathtext \& \TeX}"
else:
r = r"textpath supports mathtext & TeX"
text_path = TextPath((0, 0), r,
size=20, usetex=usetex)
p1 = PathPatch(text_path, ec="w", lw=3, fc="w", alpha=0.9,
transform=IdentityTransform())
p2 = PathPatch(text_path, ec="none", fc="k",
transform=IdentityTransform())
offsetbox2 = AuxTransformBox(IdentityTransform())
offsetbox2.add_artist(p1)
offsetbox2.add_artist(p2)
ab = AnnotationBbox(offsetbox2, (0.95, 0.05),
xycoords='axes fraction',
boxcoords="offset points",
box_alignment=(1., 0.),
frameon=False
)
ax.add_artist(ab)
ax.imshow([[0, 1, 2], [1, 2, 3]], cmap=plt.cm.gist_gray_r,
interpolation="bilinear",
aspect="auto")
# EXAMPLE 2
ax = plt.subplot(212)
arr = np.arange(256).reshape(1, 256)/256.
if usetex:
s = (r"$\displaystyle\left[\sum_{n=1}^\infty"
r"\frac{-e^{i\pi}}{2^n}\right]$!")
else:
s = r"$\left[\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}\right]$!"
text_path = TextPath((0, 0), s, size=40, usetex=usetex)
text_patch = PathClippedImagePatch(text_path, arr, ec="none",
transform=IdentityTransform())
shadow1 = mpatches.Shadow(text_patch, 1, -1,
props=dict(fc="none", ec="0.6", lw=3))
shadow2 = mpatches.Shadow(text_patch, 1, -1,
props=dict(fc="0.3", ec="none"))
# make offset box
offsetbox = AuxTransformBox(IdentityTransform())
offsetbox.add_artist(shadow1)
offsetbox.add_artist(shadow2)
offsetbox.add_artist(text_patch)
# place the anchored offset box using AnnotationBbox
ab = AnnotationBbox(offsetbox, (0.5, 0.5),
xycoords='data',
boxcoords="offset points",
box_alignment=(0.5, 0.5),
)
# text_path.set_size(10)
ax.add_artist(ab)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
|
f1ac9f907667173bd23dfed4ad1b29a1be6863a3c700399e1a15496cc08ead8d
|
"""
================
Date tick labels
================
Show how to make date plots in matplotlib using date tick locators and
formatters. See major_minor_demo1.py for more information on
controlling major and minor ticks
All matplotlib date plotting is done by converting date instances into days
since 0001-01-01 00:00:00 UTC plus one day (for historical reasons). The
conversion, tick locating and formatting is done behind the scenes so this
is most transparent to you. The dates module provides several converter
functions `matplotlib.dates.date2num` and `matplotlib.dates.num2date`.
These can convert between `datetime.datetime` objects and
:class:`numpy.datetime64` objects.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
# Load a numpy record array from yahoo csv data with fields date, open, close,
# volume, adj_close from the mpl-data/example directory. The record array
# stores the date as an np.datetime64 with a day unit ('D') in the date column.
with cbook.get_sample_data('goog.npz') as datafile:
r = np.load(datafile)['price_data'].view(np.recarray)
fig, ax = plt.subplots()
ax.plot(r.date, r.adj_close)
# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
# round to nearest years...
datemin = np.datetime64(r.date[0], 'Y')
datemax = np.datetime64(r.date[-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)
# format the coords message box
def price(x):
return '$%1.2f' % x
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
plt.show()
|
6b9e48874e1f07d5ebf5921b465b726210667e29b186f857cd2680c1649b990a
|
"""
========================
Composing Custom Legends
========================
Composing custom legends piece-by-piece.
.. note::
For more information on creating and customizing legends, see the following
pages:
* :doc:`/tutorials/intermediate/legend_guide`
* :doc:`/gallery/text_labels_and_annotations/legend_demo`
Sometimes you don't want a legend that is explicitly tied to data that
you have plotted. For example, say you have plotted 10 lines, but don't
want a legend item to show up for each one. If you simply plot the lines
and call ``ax.legend()``, you will get the following:
"""
# sphinx_gallery_thumbnail_number = 2
from matplotlib import rcParams, cycler
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
N = 10
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
data = np.array(data).T
cmap = plt.cm.coolwarm
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))
fig, ax = plt.subplots()
lines = ax.plot(data)
ax.legend(lines)
##############################################################################
# Note that one legend item per line was created.
# In this case, we can compose a legend using Matplotlib objects that aren't
# explicitly tied to the data that was plotted. For example:
from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
Line2D([0], [0], color=cmap(.5), lw=4),
Line2D([0], [0], color=cmap(1.), lw=4)]
fig, ax = plt.subplots()
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])
###############################################################################
# There are many other Matplotlib objects that can be used in this way. In the
# code below we've listed a few common ones.
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
legend_elements = [Line2D([0], [0], color='b', lw=4, label='Line'),
Line2D([0], [0], marker='o', color='w', label='Scatter',
markerfacecolor='g', markersize=15),
Patch(facecolor='orange', edgecolor='r',
label='Color Patch')]
# Create the figure
fig, ax = plt.subplots()
ax.legend(handles=legend_elements, loc='center')
plt.show()
|
aefc1e3cae1b47a000f817b048bdad5a23afb4dfad3f039c34ae9749ea1bf890
|
"""
=======================================================
Controlling style of text and labels using a dictionary
=======================================================
This example shows how to share parameters across many text objects and labels
by creating a dictionary of options passed across several functions.
"""
import numpy as np
import matplotlib.pyplot as plt
font = {'family': 'serif',
'color': 'darkred',
'weight': 'normal',
'size': 16,
}
x = np.linspace(0.0, 5.0, 100)
y = np.cos(2*np.pi*x) * np.exp(-x)
plt.plot(x, y, 'k')
plt.title('Damped exponential decay', fontdict=font)
plt.text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', fontdict=font)
plt.xlabel('time (s)', fontdict=font)
plt.ylabel('voltage (mV)', fontdict=font)
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.show()
|
f29b75e8c690d1fe757992d1da6e2ef2583a0151c818cdff698fbde33bb88bd4
|
"""
==========
Arrow Demo
==========
Arrow drawing example for the new fancy_arrow facilities.
Code contributed by: Rob Knight <[email protected]>
usage:
python arrow_demo.py realistic|full|sample|extreme
"""
import matplotlib.pyplot as plt
import numpy as np
rates_to_bases = {'r1': 'AT', 'r2': 'TA', 'r3': 'GA', 'r4': 'AG', 'r5': 'CA',
'r6': 'AC', 'r7': 'GT', 'r8': 'TG', 'r9': 'CT', 'r10': 'TC',
'r11': 'GC', 'r12': 'CG'}
numbered_bases_to_rates = {v: k for k, v in rates_to_bases.items()}
lettered_bases_to_rates = {v: 'r' + v for k, v in rates_to_bases.items()}
def make_arrow_plot(data, size=4, display='length', shape='right',
max_arrow_width=0.03, arrow_sep=0.02, alpha=0.5,
normalize_data=False, ec=None, labelcolor=None,
head_starts_at_zero=True,
rate_labels=lettered_bases_to_rates,
**kwargs):
"""Makes an arrow plot.
Parameters:
data: dict with probabilities for the bases and pair transitions.
size: size of the graph in inches.
display: 'length', 'width', or 'alpha' for arrow property to change.
shape: 'full', 'left', or 'right' for full or half arrows.
max_arrow_width: maximum width of an arrow, data coordinates.
arrow_sep: separation between arrows in a pair, data coordinates.
alpha: maximum opacity of arrows, default 0.8.
**kwargs can be anything allowed by a Arrow object, e.g.
linewidth and edgecolor.
"""
plt.xlim(-0.5, 1.5)
plt.ylim(-0.5, 1.5)
plt.gcf().set_size_inches(size, size)
plt.xticks([])
plt.yticks([])
max_text_size = size * 12
min_text_size = size
label_text_size = size * 2.5
text_params = {'ha': 'center', 'va': 'center', 'family': 'sans-serif',
'fontweight': 'bold'}
r2 = np.sqrt(2)
deltas = {
'AT': (1, 0),
'TA': (-1, 0),
'GA': (0, 1),
'AG': (0, -1),
'CA': (-1 / r2, 1 / r2),
'AC': (1 / r2, -1 / r2),
'GT': (1 / r2, 1 / r2),
'TG': (-1 / r2, -1 / r2),
'CT': (0, 1),
'TC': (0, -1),
'GC': (1, 0),
'CG': (-1, 0)}
colors = {
'AT': 'r',
'TA': 'k',
'GA': 'g',
'AG': 'r',
'CA': 'b',
'AC': 'r',
'GT': 'g',
'TG': 'k',
'CT': 'b',
'TC': 'k',
'GC': 'g',
'CG': 'b'}
label_positions = {
'AT': 'center',
'TA': 'center',
'GA': 'center',
'AG': 'center',
'CA': 'left',
'AC': 'left',
'GT': 'left',
'TG': 'left',
'CT': 'center',
'TC': 'center',
'GC': 'center',
'CG': 'center'}
def do_fontsize(k):
return float(np.clip(max_text_size * np.sqrt(data[k]),
min_text_size, max_text_size))
A = plt.text(0, 1, '$A_3$', color='r', size=do_fontsize('A'),
**text_params)
T = plt.text(1, 1, '$T_3$', color='k', size=do_fontsize('T'),
**text_params)
G = plt.text(0, 0, '$G_3$', color='g', size=do_fontsize('G'),
**text_params)
C = plt.text(1, 0, '$C_3$', color='b', size=do_fontsize('C'),
**text_params)
arrow_h_offset = 0.25 # data coordinates, empirically determined
max_arrow_length = 1 - 2 * arrow_h_offset
max_head_width = 2.5 * max_arrow_width
max_head_length = 2 * max_arrow_width
arrow_params = {'length_includes_head': True, 'shape': shape,
'head_starts_at_zero': head_starts_at_zero}
sf = 0.6 # max arrow size represents this in data coords
d = (r2 / 2 + arrow_h_offset - 0.5) / r2 # distance for diags
r2v = arrow_sep / r2 # offset for diags
# tuple of x, y for start position
positions = {
'AT': (arrow_h_offset, 1 + arrow_sep),
'TA': (1 - arrow_h_offset, 1 - arrow_sep),
'GA': (-arrow_sep, arrow_h_offset),
'AG': (arrow_sep, 1 - arrow_h_offset),
'CA': (1 - d - r2v, d - r2v),
'AC': (d + r2v, 1 - d + r2v),
'GT': (d - r2v, d + r2v),
'TG': (1 - d + r2v, 1 - d - r2v),
'CT': (1 - arrow_sep, arrow_h_offset),
'TC': (1 + arrow_sep, 1 - arrow_h_offset),
'GC': (arrow_h_offset, arrow_sep),
'CG': (1 - arrow_h_offset, -arrow_sep)}
if normalize_data:
# find maximum value for rates, i.e. where keys are 2 chars long
max_val = max((v for k, v in data.items() if len(k) == 2), default=0)
# divide rates by max val, multiply by arrow scale factor
for k, v in data.items():
data[k] = v / max_val * sf
def draw_arrow(pair, alpha=alpha, ec=ec, labelcolor=labelcolor):
# set the length of the arrow
if display == 'length':
length = (max_head_length
+ data[pair] / sf * (max_arrow_length - max_head_length))
else:
length = max_arrow_length
# set the transparency of the arrow
if display == 'alpha':
alpha = min(data[pair] / sf, alpha)
# set the width of the arrow
if display == 'width':
scale = data[pair] / sf
width = max_arrow_width * scale
head_width = max_head_width * scale
head_length = max_head_length * scale
else:
width = max_arrow_width
head_width = max_head_width
head_length = max_head_length
fc = colors[pair]
ec = ec or fc
x_scale, y_scale = deltas[pair]
x_pos, y_pos = positions[pair]
plt.arrow(x_pos, y_pos, x_scale * length, y_scale * length,
fc=fc, ec=ec, alpha=alpha, width=width,
head_width=head_width, head_length=head_length,
**arrow_params)
# figure out coordinates for text
# if drawing relative to base: x and y are same as for arrow
# dx and dy are one arrow width left and up
# need to rotate based on direction of arrow, use x_scale and y_scale
# as sin x and cos x?
sx, cx = y_scale, x_scale
where = label_positions[pair]
if where == 'left':
orig_position = 3 * np.array([[max_arrow_width, max_arrow_width]])
elif where == 'absolute':
orig_position = np.array([[max_arrow_length / 2.0,
3 * max_arrow_width]])
elif where == 'right':
orig_position = np.array([[length - 3 * max_arrow_width,
3 * max_arrow_width]])
elif where == 'center':
orig_position = np.array([[length / 2.0, 3 * max_arrow_width]])
else:
raise ValueError("Got unknown position parameter %s" % where)
M = np.array([[cx, sx], [-sx, cx]])
coords = np.dot(orig_position, M) + [[x_pos, y_pos]]
x, y = np.ravel(coords)
orig_label = rate_labels[pair]
label = r'$%s_{_{\mathrm{%s}}}$' % (orig_label[0], orig_label[1:])
plt.text(x, y, label, size=label_text_size, ha='center', va='center',
color=labelcolor or fc)
for p in sorted(positions):
draw_arrow(p)
# test data
all_on_max = dict([(i, 1) for i in 'TCAG'] +
[(i + j, 0.6) for i in 'TCAG' for j in 'TCAG'])
realistic_data = {
'A': 0.4,
'T': 0.3,
'G': 0.5,
'C': 0.2,
'AT': 0.4,
'AC': 0.3,
'AG': 0.2,
'TA': 0.2,
'TC': 0.3,
'TG': 0.4,
'CT': 0.2,
'CG': 0.3,
'CA': 0.2,
'GA': 0.1,
'GT': 0.4,
'GC': 0.1}
extreme_data = {
'A': 0.75,
'T': 0.10,
'G': 0.10,
'C': 0.05,
'AT': 0.6,
'AC': 0.3,
'AG': 0.1,
'TA': 0.02,
'TC': 0.3,
'TG': 0.01,
'CT': 0.2,
'CG': 0.5,
'CA': 0.2,
'GA': 0.1,
'GT': 0.4,
'GC': 0.2}
sample_data = {
'A': 0.2137,
'T': 0.3541,
'G': 0.1946,
'C': 0.2376,
'AT': 0.0228,
'AC': 0.0684,
'AG': 0.2056,
'TA': 0.0315,
'TC': 0.0629,
'TG': 0.0315,
'CT': 0.1355,
'CG': 0.0401,
'CA': 0.0703,
'GA': 0.1824,
'GT': 0.0387,
'GC': 0.1106}
if __name__ == '__main__':
from sys import argv
d = None
if len(argv) > 1:
if argv[1] == 'full':
d = all_on_max
scaled = False
elif argv[1] == 'extreme':
d = extreme_data
scaled = False
elif argv[1] == 'realistic':
d = realistic_data
scaled = False
elif argv[1] == 'sample':
d = sample_data
scaled = True
if d is None:
d = all_on_max
scaled = False
if len(argv) > 2:
display = argv[2]
else:
display = 'length'
size = 4
plt.figure(figsize=(size, size))
make_arrow_plot(d, display=display, linewidth=0.001, edgecolor=None,
normalize_data=scaled, head_starts_at_zero=True, size=size)
plt.show()
|
90ce8794d9b99ffc1d44e30ad8b10c1ac009c506cf7ebfead27ce66a9ce0a636
|
r"""
=================================
Using accented text in matplotlib
=================================
Matplotlib supports accented characters via TeX mathtext or unicode.
Using mathtext, the following accents are provided: \hat, \breve, \grave, \bar,
\acute, \tilde, \vec, \dot, \ddot. All of them have the same syntax,
e.g., to make an overbar you do \bar{o} or to make an o umlaut you do
\ddot{o}. The shortcuts are also provided, e.g.,: \"o \'e \`e \~n \.x
\^y
"""
import matplotlib.pyplot as plt
# Mathtext demo
fig, ax = plt.subplots()
ax.plot(range(10))
ax.set_title(r'$\ddot{o}\acute{e}\grave{e}\hat{O}'
r'\breve{i}\bar{A}\tilde{n}\vec{q}$', fontsize=20)
# Shorthand is also supported and curly braces are optional
ax.set_xlabel(r"""$\"o\ddot o \'e\`e\~n\.x\^y$""", fontsize=20)
ax.text(4, 0.5, r"$F=m\ddot{x}$")
fig.tight_layout()
# Unicode demo
fig, ax = plt.subplots()
ax.set_title("GISCARD CHAHUTÉ À L'ASSEMBLÉE")
ax.set_xlabel("LE COUP DE DÉ DE DE GAULLE")
ax.set_ylabel('André was here!')
ax.text(0.2, 0.8, 'Institut für Festkörperphysik', rotation=45)
ax.text(0.4, 0.2, 'AVA (check kerning)')
plt.show()
|
ac1fa0acf5ce959fe3fa8d140c7f94a1eca857632448446f4d3bdd52f2274539
|
"""
============
Rainbow text
============
The example shows how to string together several text objects.
History
-------
On the matplotlib-users list back in February 2012, Gökhan Sever asked the
following question:
Is there a way in matplotlib to partially specify the color of a string?
Example:
plt.ylabel("Today is cloudy.")
How can I show "today" as red, "is" as green and "cloudy." as blue?
Thanks.
Paul Ivanov responded with this answer:
"""
import matplotlib.pyplot as plt
from matplotlib import transforms
def rainbow_text(x, y, strings, colors, orientation='horizontal',
ax=None, **kwargs):
"""
Take a list of *strings* and *colors* and place them next to each
other, with text strings[i] being shown in colors[i].
Parameters
----------
x, y : float
Text position in data coordinates.
strings : list of str
The strings to draw.
colors : list of color
The colors to use.
orientation : {'horizontal', 'vertical'}
ax : Axes, optional
The Axes to draw into. If None, the current axes will be used.
**kwargs
All other keyword arguments are passed to plt.text(), so you can
set the font size, family, etc.
"""
if ax is None:
ax = plt.gca()
t = ax.transData
canvas = ax.figure.canvas
assert orientation in ['horizontal', 'vertical']
if orientation == 'vertical':
kwargs.update(rotation=90, verticalalignment='bottom')
for s, c in zip(strings, colors):
text = ax.text(x, y, s + " ", color=c, transform=t, **kwargs)
# Need to draw to update the text position.
text.draw(canvas.get_renderer())
ex = text.get_window_extent()
if orientation == 'horizontal':
t = transforms.offset_copy(
text.get_transform(), x=ex.width, units='dots')
else:
t = transforms.offset_copy(
text.get_transform(), y=ex.height, units='dots')
words = "all unicorns poop rainbows ! ! !".split()
colors = ['red', 'orange', 'gold', 'lawngreen', 'lightseagreen', 'royalblue',
'blueviolet']
plt.figure(figsize=(6, 6))
rainbow_text(0.1, 0.05, words, colors, size=18)
rainbow_text(0.05, 0.1, words, colors, orientation='vertical', size=18)
plt.show()
|
88a2e150e2d6c1f5fc8d0548cb9766af767d88e32df3fd54d8f6ee2ae2281467
|
r"""
=========================================
The difference between \\dfrac and \\frac
=========================================
In this example, the differences between the \\dfrac and \\frac TeX macros are
illustrated; in particular, the difference between display style and text style
fractions when using Mathtex.
.. versionadded:: 2.1
.. note::
To use \\dfrac with the LaTeX engine (text.usetex : True), you need to
import the amsmath package with the text.latex.preamble rc, which is
an unsupported feature; therefore, it is probably a better idea to just
use the \\displaystyle option before the \\frac macro to get this behavior
with the LaTeX engine.
"""
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(5.25, 0.75))
fig.text(0.5, 0.3, r'\dfrac: $\dfrac{a}{b}$',
horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.7, r'\frac: $\frac{a}{b}$',
horizontalalignment='center', verticalalignment='center')
plt.show()
|
fef439be8669648872b25caf43516ad0100c386f05019b4f546bdfe0d17b5fd0
|
"""
==================================
Fonts demo (object-oriented style)
==================================
Set font properties using setters.
See :doc:`fonts_demo_kw` to achieve the same effect using kwargs.
"""
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
plt.subplot(111, facecolor='w')
font0 = FontProperties()
alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}
# Show family options
families = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
font1 = font0.copy()
font1.set_size('large')
t = plt.text(-0.8, 0.9, 'family', fontproperties=font1,
**alignment)
yp = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
for k, family in enumerate(families):
font = font0.copy()
font.set_family(family)
t = plt.text(-0.8, yp[k], family, fontproperties=font,
**alignment)
# Show style options
styles = ['normal', 'italic', 'oblique']
t = plt.text(-0.4, 0.9, 'style', fontproperties=font1,
**alignment)
for k, style in enumerate(styles):
font = font0.copy()
font.set_family('sans-serif')
font.set_style(style)
t = plt.text(-0.4, yp[k], style, fontproperties=font,
**alignment)
# Show variant options
variants = ['normal', 'small-caps']
t = plt.text(0.0, 0.9, 'variant', fontproperties=font1,
**alignment)
for k, variant in enumerate(variants):
font = font0.copy()
font.set_family('serif')
font.set_variant(variant)
t = plt.text(0.0, yp[k], variant, fontproperties=font,
**alignment)
# Show weight options
weights = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
t = plt.text(0.4, 0.9, 'weight', fontproperties=font1,
**alignment)
for k, weight in enumerate(weights):
font = font0.copy()
font.set_weight(weight)
t = plt.text(0.4, yp[k], weight, fontproperties=font,
**alignment)
# Show size options
sizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
'x-large', 'xx-large']
t = plt.text(0.8, 0.9, 'size', fontproperties=font1,
**alignment)
for k, size in enumerate(sizes):
font = font0.copy()
font.set_size(size)
t = plt.text(0.8, yp[k], size, fontproperties=font,
**alignment)
# Show bold italic
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('x-small')
t = plt.text(-0.4, 0.1, 'bold italic', fontproperties=font,
**alignment)
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('medium')
t = plt.text(-0.4, 0.2, 'bold italic', fontproperties=font,
**alignment)
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('x-large')
t = plt.text(-0.4, 0.3, 'bold italic', fontproperties=font,
**alignment)
plt.axis([-1, 1, 0, 1])
plt.show()
|
e5e7c70a9581ada6b8af6c2da70b0b643742844467d7562d3a807450042c808d
|
"""===================
Demo Annotation Box
===================
The AnnotationBbox Artist creates an annotation using an OffsetBox. This
example demonstrates three different OffsetBoxes: TextArea, DrawingArea and
OffsetImage. AnnotationBbox gives more fine-grained control than using the axes
method annotate.
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
AnnotationBbox)
from matplotlib.cbook import get_sample_data
fig, ax = plt.subplots()
# Define a 1st position to annotate (display it with a marker)
xy = (0.5, 0.7)
ax.plot(xy[0], xy[1], ".r")
# Annotate the 1st position with a text box ('Test 1')
offsetbox = TextArea("Test 1", minimumdescent=False)
ab = AnnotationBbox(offsetbox, xy,
xybox=(-20, 40),
xycoords='data',
boxcoords="offset points",
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
# Annotate the 1st position with another text box ('Test')
offsetbox = TextArea("Test", minimumdescent=False)
ab = AnnotationBbox(offsetbox, xy,
xybox=(1.02, xy[1]),
xycoords='data',
boxcoords=("axes fraction", "data"),
box_alignment=(0., 0.5),
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
# Define a 2nd position to annotate (don't display with a marker this time)
xy = [0.3, 0.55]
# Annotate the 2nd position with a circle patch
da = DrawingArea(20, 20, 0, 0)
p = Circle((10, 10), 10)
da.add_artist(p)
ab = AnnotationBbox(da, xy,
xybox=(1.02, xy[1]),
xycoords='data',
boxcoords=("axes fraction", "data"),
box_alignment=(0., 0.5),
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
# Annotate the 2nd position with an image (a generated array of pixels)
arr = np.arange(100).reshape((10, 10))
im = OffsetImage(arr, zoom=2)
im.image.axes = ax
ab = AnnotationBbox(im, xy,
xybox=(-50., 50.),
xycoords='data',
boxcoords="offset points",
pad=0.3,
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
# Annotate the 2nd position with another image (a Grace Hopper portrait)
with get_sample_data("grace_hopper.png") as file:
arr_img = plt.imread(file, format='png')
imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax
ab = AnnotationBbox(imagebox, xy,
xybox=(120., -80.),
xycoords='data',
boxcoords="offset points",
pad=0.5,
arrowprops=dict(
arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=90,rad=3")
)
ax.add_artist(ab)
# Fix the display limits to see everything
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods and classes is shown in this
# example:
Circle
TextArea
DrawingArea
OffsetImage
AnnotationBbox
get_sample_data
plt.subplots
plt.imread
plt.show
|
64e7c0e6f5d9d58cc1d55dab1dde32ae7dde1a0b09e53a0b0b8d396743247e83
|
"""
=================================
Rendering math equation using TeX
=================================
You can use TeX to render all of your matplotlib text if the rc
parameter ``text.usetex`` is set. This works currently on the agg and ps
backends, and requires that you have tex and the other dependencies
described in the :doc:`/tutorials/text/usetex` tutorial
properly installed on your system. The first time you run a script
you will see a lot of output from tex and associated tools. The next
time, the run may be silent, as a lot of the information is cached.
Notice how the label for the y axis is provided using unicode!
"""
import numpy as np
import matplotlib
matplotlib.rcParams['text.usetex'] = True
import matplotlib.pyplot as plt
t = np.linspace(0.0, 1.0, 100)
s = np.cos(4 * np.pi * t) + 2
fig, ax = plt.subplots(figsize=(6, 4), tight_layout=True)
ax.plot(t, s)
ax.set_xlabel(r'\textbf{time (s)}')
ax.set_ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}', fontsize=16)
ax.set_title(r'\TeX\ is Number $\displaystyle\sum_{n=1}^\infty'
r'\frac{-e^{i\pi}}{2^n}$!', fontsize=16, color='r')
plt.show()
|
6299e6900445f23e3eef5181e9b5fb3cbe2c7259ca5026df410d6345bbd40ad9
|
"""
====================
Usetex Baseline Test
====================
"""
import matplotlib.pyplot as plt
import matplotlib.axes as maxes
from matplotlib import rcParams
rcParams['text.usetex'] = True
class Axes(maxes.Axes):
"""
A hackish way to simultaneously draw texts w/ usetex=True and
usetex=False in the same figure. It does not work in the ps backend.
"""
def __init__(self, *args, usetex=False, preview=False, **kwargs):
self.usetex = usetex
self.preview = preview
super().__init__(*args, **kwargs)
def draw(self, renderer):
with plt.rc_context({"text.usetex": self.usetex,
"text.latex.preview": self.preview}):
super().draw(renderer)
subplot = maxes.subplot_class_factory(Axes)
def test_window_extent(ax, usetex, preview):
va = "baseline"
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
text_kw = dict(va=va,
size=50,
bbox=dict(pad=0., ec="k", fc="none"))
test_strings = ["lg", r"$\frac{1}{2}\pi$",
r"$p^{3^A}$", r"$p_{3_2}$"]
ax.axvline(0, color="r")
for i, s in enumerate(test_strings):
ax.axhline(i, color="r")
ax.text(0., 3 - i, s, **text_kw)
ax.set_xlim(-0.1, 1.1)
ax.set_ylim(-.8, 3.9)
ax.set_title("usetex=%s\npreview=%s" % (str(usetex), str(preview)))
fig = plt.figure(figsize=(2 * 3, 6.5))
for i, usetex, preview in [[0, False, False],
[1, True, False],
[2, True, True]]:
ax = subplot(fig, 1, 3, i + 1, usetex=usetex, preview=preview)
fig.add_subplot(ax)
fig.subplots_adjust(top=0.85)
test_window_extent(ax, usetex=usetex, preview=preview)
plt.show()
|
8c6c9ced5e0307552ff328bcb1e39754178214fd7fd2317ae87e3af27637b4fa
|
"""
===================
Fonts demo (kwargs)
===================
Set font properties using kwargs.
See :doc:`fonts_demo` to achieve the same effect using setters.
"""
import matplotlib.pyplot as plt
plt.subplot(111, facecolor='w')
alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}
# Show family options
families = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
t = plt.text(-0.8, 0.9, 'family', size='large', **alignment)
yp = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
for k, family in enumerate(families):
t = plt.text(-0.8, yp[k], family, family=family, **alignment)
# Show style options
styles = ['normal', 'italic', 'oblique']
t = plt.text(-0.4, 0.9, 'style', **alignment)
for k, style in enumerate(styles):
t = plt.text(-0.4, yp[k], style, family='sans-serif', style=style,
**alignment)
# Show variant options
variants = ['normal', 'small-caps']
t = plt.text(0.0, 0.9, 'variant', **alignment)
for k, variant in enumerate(variants):
t = plt.text(0.0, yp[k], variant, family='serif', variant=variant,
**alignment)
# Show weight options
weights = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
t = plt.text(0.4, 0.9, 'weight', **alignment)
for k, weight in enumerate(weights):
t = plt.text(0.4, yp[k], weight, weight=weight,
**alignment)
# Show size options
sizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
'x-large', 'xx-large']
t = plt.text(0.8, 0.9, 'size', **alignment)
for k, size in enumerate(sizes):
t = plt.text(0.8, yp[k], size, size=size,
**alignment)
x = -0.4
# Show bold italic
t = plt.text(x, 0.1, 'bold italic', style='italic',
weight='bold', size='x-small',
**alignment)
t = plt.text(x, 0.2, 'bold italic',
style='italic', weight='bold', size='medium',
**alignment)
t = plt.text(x, 0.3, 'bold italic',
style='italic', weight='bold', size='x-large',
**alignment)
plt.axis([-1, 1, 0, 1])
plt.show()
|
29931039f09c29fbc62c04afe4b1dbaa07bb92c2cb6ee23c89fd6f821a88dda7
|
"""
==========
Font table
==========
Matplotlib's font support is provided by the FreeType library.
Here, we use `~.Axes.table` to draw a table that shows the glyphs by Unicode
codepoint. For brevity, the table only contains the first 256 glyphs.
The example is a full working script. You can download it and use it to
investigate a font by running ::
python font_table.py /path/to/font/file
"""
import unicodedata
import matplotlib.font_manager as fm
from matplotlib.ft2font import FT2Font
import matplotlib.pyplot as plt
def print_glyphs(path):
"""
Print the all glyphs in the given font file to stdout.
Parameters
----------
path : str or None
The path to the font file. If None, use Matplotlib's default font.
"""
if path is None:
path = fm.findfont(fm.FontProperties()) # The default font.
font = FT2Font(path)
charmap = font.get_charmap()
max_indices_len = len(str(max(charmap.values())))
print("The font face contains the following glyphs:")
for char_code, glyph_index in charmap.items():
char = chr(char_code)
name = unicodedata.name(
char,
f"{char_code:#x} ({font.get_glyph_name(glyph_index)})")
print(f"{glyph_index:>{max_indices_len}} {char} {name}")
def draw_font_table(path):
"""
Draw a font table of the first 255 chars of the given font.
Parameters
----------
path : str or None
The path to the font file. If None, use Matplotlib's default font.
"""
if path is None:
path = fm.findfont(fm.FontProperties()) # The default font.
font = FT2Font(path)
# A charmap is a mapping of "character codes" (in the sense of a character
# encoding, e.g. latin-1) to glyph indices (i.e. the internal storage table
# of the font face).
# In FreeType>=2.1, a Unicode charmap (i.e. mapping Unicode codepoints)
# is selected by default. Moreover, recent versions of FreeType will
# automatically synthesize such a charmap if the font does not include one
# (this behavior depends on the font format; for example it is present
# since FreeType 2.0 for Type 1 fonts but only since FreeType 2.8 for
# TrueType (actually, SFNT) fonts).
# The code below (specifically, the ``chr(char_code)`` call) assumes that
# we have indeed selected a Unicode charmap.
codes = font.get_charmap().items()
labelc = ["{:X}".format(i) for i in range(16)]
labelr = ["{:02X}".format(16 * i) for i in range(16)]
chars = [["" for c in range(16)] for r in range(16)]
for char_code, glyph_index in codes:
if char_code >= 256:
continue
row, col = divmod(char_code, 16)
chars[row][col] = chr(char_code)
fig, ax = plt.subplots(figsize=(8, 4))
ax.set_title(path)
ax.set_axis_off()
table = ax.table(
cellText=chars,
rowLabels=labelr,
colLabels=labelc,
rowColours=["palegreen"] * 16,
colColours=["palegreen"] * 16,
cellColours=[[".95" for c in range(16)] for r in range(16)],
cellLoc='center',
loc='upper left',
)
for key, cell in table.get_celld().items():
row, col = key
if row > 0 and col > -1: # Beware of table's idiosyncratic indexing...
cell.set_text_props(fontproperties=fm.FontProperties(fname=path))
fig.tight_layout()
plt.show()
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser(description="Display a font table.")
parser.add_argument("path", nargs="?", help="Path to the font file.")
parser.add_argument("--print-all", action="store_true",
help="Additionally, print all chars to stdout.")
args = parser.parse_args()
if args.print_all:
print_glyphs(args.path)
draw_font_table(args.path)
|
fd72ac71f99086e427fb87c83d60330a80d42be7eb69f094b0622e883c5023da
|
"""
===========================
Configuring the font family
===========================
You can explicitly set which font family is picked up for a given font
style (e.g., 'serif', 'sans-serif', or 'monospace').
In the example below, we only allow one font family (Tahoma) for the
sans-serif font style. You the default family with the font.family rc
param, e.g.,::
rcParams['font.family'] = 'sans-serif'
and for the font.family you set a list of font styles to try to find
in order::
rcParams['font.sans-serif'] = ['Tahoma', 'DejaVu Sans',
'Lucida Grande', 'Verdana']
"""
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Tahoma']
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], label='test')
ax.legend()
plt.show()
|
1e2f8d09e84966aba2171a26f45bdf5eda1b7aa07d6f90e0b928943c415a7d2c
|
"""
===========
Legend Demo
===========
Plotting legends in Matplotlib.
There are many ways to create and customize legends in Matplotlib. Below
we'll show a few examples for how to do so.
First we'll show off how to make a legend for specific lines.
"""
import matplotlib.pyplot as plt
import matplotlib.collections as mcol
from matplotlib.legend_handler import HandlerLineCollection, HandlerTuple
from matplotlib.lines import Line2D
import numpy as np
t1 = np.arange(0.0, 2.0, 0.1)
t2 = np.arange(0.0, 2.0, 0.01)
fig, ax = plt.subplots()
# note that plot returns a list of lines. The "l1, = plot" usage
# extracts the first element of the list into l1 using tuple
# unpacking. So l1 is a Line2D instance, not a sequence of lines
l1, = ax.plot(t2, np.exp(-t2))
l2, l3 = ax.plot(t2, np.sin(2 * np.pi * t2), '--o', t1, np.log(1 + t1), '.')
l4, = ax.plot(t2, np.exp(-t2) * np.sin(2 * np.pi * t2), 's-.')
ax.legend((l2, l4), ('oscillatory', 'damped'), loc='upper right', shadow=True)
ax.set_xlabel('time')
ax.set_ylabel('volts')
ax.set_title('Damped oscillation')
plt.show()
###############################################################################
# Next we'll demonstrate plotting more complex labels.
x = np.linspace(0, 1)
fig, (ax0, ax1) = plt.subplots(2, 1)
# Plot the lines y=x**n for n=1..4.
for n in range(1, 5):
ax0.plot(x, x**n, label="n={0}".format(n))
leg = ax0.legend(loc="upper left", bbox_to_anchor=[0, 1],
ncol=2, shadow=True, title="Legend", fancybox=True)
leg.get_title().set_color("red")
# Demonstrate some more complex labels.
ax1.plot(x, x**2, label="multi\nline")
half_pi = np.linspace(0, np.pi / 2)
ax1.plot(np.sin(half_pi), np.cos(half_pi), label=r"$\frac{1}{2}\pi$")
ax1.plot(x, 2**(x**2), label="$2^{x^2}$")
ax1.legend(shadow=True, fancybox=True)
plt.show()
###############################################################################
# Here we attach legends to more complex plots.
fig, axes = plt.subplots(3, 1, constrained_layout=True)
top_ax, middle_ax, bottom_ax = axes
top_ax.bar([0, 1, 2], [0.2, 0.3, 0.1], width=0.4, label="Bar 1",
align="center")
top_ax.bar([0.5, 1.5, 2.5], [0.3, 0.2, 0.2], color="red", width=0.4,
label="Bar 2", align="center")
top_ax.legend()
middle_ax.errorbar([0, 1, 2], [2, 3, 1], xerr=0.4, fmt="s", label="test 1")
middle_ax.errorbar([0, 1, 2], [3, 2, 4], yerr=0.3, fmt="o", label="test 2")
middle_ax.errorbar([0, 1, 2], [1, 1, 3], xerr=0.4, yerr=0.3, fmt="^",
label="test 3")
middle_ax.legend()
bottom_ax.stem([0.3, 1.5, 2.7], [1, 3.6, 2.7], label="stem test")
bottom_ax.legend()
plt.show()
###############################################################################
# Now we'll showcase legend entries with more than one legend key.
fig, (ax1, ax2) = plt.subplots(2, 1, constrained_layout=True)
# First plot: two legend keys for a single entry
p1 = ax1.scatter([1], [5], c='r', marker='s', s=100)
p2 = ax1.scatter([3], [2], c='b', marker='o', s=100)
# `plot` returns a list, but we want the handle - thus the comma on the left
p3, = ax1.plot([1, 5], [4, 4], 'm-d')
# Assign two of the handles to the same legend entry by putting them in a tuple
# and using a generic handler map (which would be used for any additional
# tuples of handles like (p1, p3)).
l = ax1.legend([(p1, p3), p2], ['two keys', 'one key'], scatterpoints=1,
numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)})
# Second plot: plot two bar charts on top of each other and change the padding
# between the legend keys
x_left = [1, 2, 3]
y_pos = [1, 3, 2]
y_neg = [2, 1, 4]
rneg = ax2.bar(x_left, y_neg, width=0.5, color='w', hatch='///', label='-1')
rpos = ax2.bar(x_left, y_pos, width=0.5, color='k', label='+1')
# Treat each legend entry differently by using specific `HandlerTuple`s
l = ax2.legend([(rpos, rneg), (rneg, rpos)], ['pad!=0', 'pad=0'],
handler_map={(rpos, rneg): HandlerTuple(ndivide=None),
(rneg, rpos): HandlerTuple(ndivide=None, pad=0.)})
plt.show()
###############################################################################
# Finally, it is also possible to write custom objects that define
# how to stylize legends.
class HandlerDashedLines(HandlerLineCollection):
"""
Custom Handler for LineCollection instances.
"""
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
# figure out how many lines there are
numlines = len(orig_handle.get_segments())
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
leglines = []
# divide the vertical space where the lines will go
# into equal parts based on the number of lines
ydata = np.full_like(xdata, height / (numlines + 1))
# for each line, create the line at the proper location
# and set the dash pattern
for i in range(numlines):
legline = Line2D(xdata, ydata * (numlines - i) - ydescent)
self.update_prop(legline, orig_handle, legend)
# set color, dash pattern, and linewidth to that
# of the lines in linecollection
try:
color = orig_handle.get_colors()[i]
except IndexError:
color = orig_handle.get_colors()[0]
try:
dashes = orig_handle.get_dashes()[i]
except IndexError:
dashes = orig_handle.get_dashes()[0]
try:
lw = orig_handle.get_linewidths()[i]
except IndexError:
lw = orig_handle.get_linewidths()[0]
if dashes[0] is not None:
legline.set_dashes(dashes[1])
legline.set_color(color)
legline.set_transform(trans)
legline.set_linewidth(lw)
leglines.append(legline)
return leglines
x = np.linspace(0, 5, 100)
fig, ax = plt.subplots()
colors = plt.rcParams['axes.prop_cycle'].by_key()['color'][:5]
styles = ['solid', 'dashed', 'dashed', 'dashed', 'solid']
lines = []
for i, color, style in zip(range(5), colors, styles):
ax.plot(x, np.sin(x) - .1 * i, c=color, ls=style)
# make proxy artists
# make list of one line -- doesn't matter what the coordinates are
line = [[(0, 0)]]
# set up the proxy artist
lc = mcol.LineCollection(5 * line, linestyles=styles, colors=colors)
# create the legend
ax.legend([lc], ['multi-line'], handler_map={type(lc): HandlerDashedLines()},
handlelength=2.5, handleheight=3)
plt.show()
|
f24e76fbe6d57a92a4514bf66d2fc172c255513f7120f38f7a5cbd37115f4773
|
"""
=======================
Artist within an artist
=======================
Override basic methods so an artist can contain another
artist. In this case, the line contains a Text instance to label it.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.transforms as mtransforms
import matplotlib.text as mtext
class MyLine(lines.Line2D):
def __init__(self, *args, **kwargs):
# we'll update the position when the line data is set
self.text = mtext.Text(0, 0, '')
lines.Line2D.__init__(self, *args, **kwargs)
# we can't access the label attr until *after* the line is
# initiated
self.text.set_text(self.get_label())
def set_figure(self, figure):
self.text.set_figure(figure)
lines.Line2D.set_figure(self, figure)
def set_axes(self, axes):
self.text.set_axes(axes)
lines.Line2D.set_axes(self, axes)
def set_transform(self, transform):
# 2 pixel offset
texttrans = transform + mtransforms.Affine2D().translate(2, 2)
self.text.set_transform(texttrans)
lines.Line2D.set_transform(self, transform)
def set_data(self, x, y):
if len(x):
self.text.set_position((x[-1], y[-1]))
lines.Line2D.set_data(self, x, y)
def draw(self, renderer):
# draw my label at the end of the line with 2 pixel offset
lines.Line2D.draw(self, renderer)
self.text.draw(renderer)
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
x, y = np.random.rand(2, 20)
line = MyLine(x, y, mfc='red', ms=12, label='line label')
#line.text.set_text('line label')
line.text.set_color('red')
line.text.set_fontsize(16)
ax.add_line(line)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.lines
matplotlib.lines.Line2D
matplotlib.lines.Line2D.set_data
matplotlib.artist
matplotlib.artist.Artist
matplotlib.artist.Artist.draw
matplotlib.artist.Artist.set_transform
matplotlib.text
matplotlib.text.Text
matplotlib.text.Text.set_color
matplotlib.text.Text.set_fontsize
matplotlib.text.Text.set_position
matplotlib.axes.Axes.add_line
matplotlib.transforms
matplotlib.transforms.Affine2D
|
556cdbd0269f611b0978e5264b806407dd8332e5e05ddff8828acbfaa1466bb3
|
"""
===============================
Legend using pre-defined labels
===============================
Defining legend labels with plots.
"""
import numpy as np
import matplotlib.pyplot as plt
# Make some fake data.
a = b = np.arange(0, 3, .02)
c = np.exp(a)
d = c[::-1]
# Create plots with pre-defined labels.
fig, ax = plt.subplots()
ax.plot(a, c, 'k--', label='Model length')
ax.plot(a, d, 'k:', label='Data length')
ax.plot(a, c + d, 'k', label='Total message length')
legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')
# Put a nicer background color on the legend.
legend.get_frame().set_facecolor('C0')
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.axes.Axes.plot
matplotlib.pyplot.plot
matplotlib.axes.Axes.legend
matplotlib.pyplot.legend
|
bcf4e6e260eddb9ccf8a9a12e86792d9696bead1461243e6d046a350f3b528e9
|
"""
=============
Unicode minus
=============
You can use the proper typesetting `Unicode minus`__ or the ASCII hyphen for
minus, which some people prefer. :rc:`axes.unicode_minus` controls the default
behavior.
__ https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes
The default is to use the Unicode minus.
"""
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
matplotlib.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots()
ax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')
ax.set_title('Using hyphen instead of Unicode minus')
plt.show()
|
799c85436de87fe1f3d35926aa44dfe7d8f7f7d247f05f1ee92af6febc5b67cc
|
"""
==============
Scatter Masked
==============
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()
|
c9c77dae5da1c4fb3951b8a79b86e6419453d4f45e1be4084d61f9a42ee4ffb0
|
"""
====================
Horizontal bar chart
====================
This example showcases a simple horizontal bar chart.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
plt.rcdefaults()
fig, ax = plt.subplots()
# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))
ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis() # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
plt.show()
|
b76d1df248a2e554191a14b54722155cd88b47f6aae992fea35723a9826884a9
|
"""
=============================
Grouped bar chart with labels
=============================
Bar charts are useful for visualizing counts, or summary statistics
with error bars. This example shows a ways to create a grouped bar chart
with Matplotlib and also how to annotate bars with labels.
"""
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
ind = np.arange(len(men_means)) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
label='Women')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()
def autolabel(rects, xpos='center'):
"""
Attach a text label above each bar in *rects*, displaying its height.
*xpos* indicates which side to place the text w.r.t. the center of
the bar. It can be one of the following {'center', 'right', 'left'}.
"""
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0, 'right': 1, 'left': -1}
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(offset[xpos]*3, 3), # use 3 points offset
textcoords="offset points", # in both directions
ha=ha[xpos], va='bottom')
autolabel(rects1, "left")
autolabel(rects2, "right")
fig.tight_layout()
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods and classes is shown
# in this example:
matplotlib.axes.Axes.bar
matplotlib.pyplot.bar
matplotlib.axes.Axes.annotate
matplotlib.pyplot.annotate
|
7bc76d575a3e91c286a8fd20aed2eeee8b2f215e55498d175f2d0b1aae915fcf
|
'''
===========
Masked Demo
===========
Plot lines with points masked out.
This would typically be used with gappy data, to
break the line at the data gaps.
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 2*np.pi, 0.02)
y = np.sin(x)
y1 = np.sin(2*x)
y2 = np.sin(3*x)
ym1 = np.ma.masked_where(y1 > 0.5, y1)
ym2 = np.ma.masked_where(y2 < -0.5, y2)
lines = plt.plot(x, y, x, ym1, x, ym2, 'o')
plt.setp(lines[0], linewidth=4)
plt.setp(lines[1], linewidth=2)
plt.setp(lines[2], markersize=10)
plt.legend(('No mask', 'Masked if > 0.5', 'Masked if < -0.5'),
loc='upper right')
plt.title('Masked line demo')
plt.show()
|
fec2c0d0f962d44ae402b15543c6ea4f16c11db89a9ba4997de662792033e366
|
"""
============
Scatter Hist
============
Creates histogram from scatter plot
and adds them to the sides of the plot.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
# Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
nullfmt = NullFormatter() # no labels
# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02
rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]
# start with a rectangular Figure
plt.figure(figsize=(8, 8))
axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)
# no labels
axHistx.xaxis.set_major_formatter(nullfmt)
axHisty.yaxis.set_major_formatter(nullfmt)
# the scatter plot:
axScatter.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
axScatter.set_xlim((-lim, lim))
axScatter.set_ylim((-lim, lim))
bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')
axHistx.set_xlim(axScatter.get_xlim())
axHisty.set_ylim(axScatter.get_ylim())
plt.show()
|
32a39f26312003bd53395d3ccf1046b97478ef6dabd8c6ec071f4df2d0efe75d
|
"""
==================
Fill Betweenx Demo
==================
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()
|
f68001f35a16db99092ca1609eb6204fbdc5f042dbdba41de67db400f599d851
|
"""
===============================================
Creating a 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.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
from datetime import datetime
try:
# Try to fetch a list of Matplotlib releases and their dates
# from https://api.github.com/repos/matplotlib/matplotlib/releases
import urllib.request
import json
url = 'https://api.github.com/repos/matplotlib/matplotlib/releases'
url += '?per_page=100'
data = json.loads(urllib.request.urlopen(url, timeout=.4).read().decode())
dates = []
names = []
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])
names.append(item['tag_name'])
# Convert date strings (e.g. 2014-10-18) to datetime
dates = [datetime.strptime(d, "%Y-%m-%d") for d in dates]
except Exception:
# In case the above fails, e.g. because of missing internet connection
# use the following lists as fallback.
names = ['v2.2.4', 'v3.0.3', 'v3.0.2', 'v3.0.1', 'v3.0.0', 'v2.2.3',
'v2.2.2', 'v2.2.1', 'v2.2.0', 'v2.1.2', 'v2.1.1', 'v2.1.0',
'v2.0.2', 'v2.0.1', 'v2.0.0', 'v1.5.3', 'v1.5.2', 'v1.5.1',
'v1.5.0', 'v1.4.3', 'v1.4.2', 'v1.4.1', 'v1.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']
# Convert date strings (e.g. 2014-10-18) to datetime
dates = [datetime.strptime(d, "%Y-%m-%d") for d in dates]
##############################################################################
# Next, we'll create a `~.Axes.stem` plot with some variation in levels as to
# distinguish even close-by events. In contrast to a usual stem plot, we will
# shift the markers to the baseline for visual emphasis on the one-dimensional
# nature of the time line.
# 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
levels = np.tile([-5, 5, -3, 3, -1, 1],
int(np.ceil(len(dates)/6)))[:len(dates)]
# Create figure and plot a stem plot with the date
fig, ax = plt.subplots(figsize=(8.8, 4), constrained_layout=True)
ax.set(title="Matplotlib release dates")
markerline, stemline, baseline = ax.stem(dates, levels,
linefmt="C3-", basefmt="k-",
use_line_collection=True)
plt.setp(markerline, mec="k", mfc="w", zorder=3)
# Shift the markers to the baseline by replacing the y-data by zeros.
markerline.set_ydata(np.zeros(len(dates)))
# annotate lines
vert = np.array(['top', 'bottom'])[(levels > 0).astype(int)]
for d, l, r, va in zip(dates, levels, names, vert):
ax.annotate(r, xy=(d, l), xytext=(-3, np.sign(l)*3),
textcoords="offset points", va=va, ha="right")
# format xaxis with 4 month intervals
ax.get_xaxis().set_major_locator(mdates.MonthLocator(interval=4))
ax.get_xaxis().set_major_formatter(mdates.DateFormatter("%b %Y"))
plt.setp(ax.get_xticklabels(), rotation=30, ha="right")
# remove y axis and spines
ax.get_yaxis().set_visible(False)
for spine in ["left", "top", "right"]:
ax.spines[spine].set_visible(False)
ax.margins(y=0.1)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods and classes is shown
# in this example:
import matplotlib
matplotlib.axes.Axes.stem
matplotlib.axes.Axes.annotate
matplotlib.axis.Axis.set_major_locator
matplotlib.axis.Axis.set_major_formatter
matplotlib.dates.MonthLocator
matplotlib.dates.DateFormatter
|
2d3102b9f664849aaa17e218723cebd5eef8a31234fcf7a5b14cac6c2cd2d90d
|
"""
==================
Errorbar Subsample
==================
Demo for the errorevery keyword to show data full accuracy data plots with
few errorbars.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.1)
y = np.exp(-x)
# example variable error bar values
yerr = 0.1 + 0.1 * np.sqrt(x)
# Now switch to a more OO interface to exercise more features.
fig, axs = plt.subplots(nrows=1, ncols=2, sharex=True)
ax = axs[0]
ax.errorbar(x, y, yerr=yerr)
ax.set_title('all errorbars')
ax = axs[1]
ax.errorbar(x, y, yerr=yerr, errorevery=5)
ax.set_title('only every 5th errorbar')
fig.suptitle('Errorbar subsampling for better appearance')
plt.show()
|
2334f51061efc29c669a41c379e379af3b9d3ba436bcc1e9dcac7e48f3fc5ede
|
"""
==============
Eventplot Demo
==============
An eventplot showing sequences of events with various line properties.
The plot is shown in both horizontal and vertical orientations.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
matplotlib.rcParams['font.size'] = 8.0
# Fixing random state for reproducibility
np.random.seed(19680801)
# create random data
data1 = np.random.random([6, 50])
# set different colors for each set of positions
colors1 = ['C{}'.format(i) for i in range(6)]
# set different line properties for each set of positions
# note that some overlap
lineoffsets1 = np.array([-15, -3, 1, 1.5, 6, 10])
linelengths1 = [5, 2, 1, 1, 3, 1.5]
fig, axs = plt.subplots(2, 2)
# create a horizontal plot
axs[0, 0].eventplot(data1, colors=colors1, lineoffsets=lineoffsets1,
linelengths=linelengths1)
# create a vertical plot
axs[1, 0].eventplot(data1, colors=colors1, lineoffsets=lineoffsets1,
linelengths=linelengths1, orientation='vertical')
# create another set of random data.
# the gamma distribution is only used fo aesthetic purposes
data2 = np.random.gamma(4, size=[60, 50])
# use individual values for the parameters this time
# these values will be used for all data sets (except lineoffsets2, which
# sets the increment between each data set in this usage)
colors2 = 'black'
lineoffsets2 = 1
linelengths2 = 1
# create a horizontal plot
axs[0, 1].eventplot(data2, colors=colors2, lineoffsets=lineoffsets2,
linelengths=linelengths2)
# create a vertical plot
axs[1, 1].eventplot(data2, colors=colors2, lineoffsets=lineoffsets2,
linelengths=linelengths2, orientation='vertical')
plt.show()
|
1b20bd10ab8fc8edf78497f6db5a632727c466162601f6bf380cd8e10bf25879
|
"""
=====================================
Plotting the coherence of two signals
=====================================
An example showing how to plot the coherence of two signals.
"""
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
dt = 0.01
t = np.arange(0, 30, dt)
nse1 = np.random.randn(len(t)) # white noise 1
nse2 = np.random.randn(len(t)) # white noise 2
# Two signals with a coherent part at 10Hz and a random part
s1 = np.sin(2 * np.pi * 10 * t) + nse1
s2 = np.sin(2 * np.pi * 10 * t) + nse2
fig, axs = plt.subplots(2, 1)
axs[0].plot(t, s1, t, s2)
axs[0].set_xlim(0, 2)
axs[0].set_xlabel('time')
axs[0].set_ylabel('s1 and s2')
axs[0].grid(True)
cxy, f = axs[1].cohere(s1, s2, 256, 1. / dt)
axs[1].set_ylabel('coherence')
fig.tight_layout()
plt.show()
|
1562a088ac1e98fe5eff0feb91a14ff4324605c8966f2c1b52b28f34f3da35cc
|
"""
=========
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, use_line_collection=True)
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, use_line_collection=True)
markerline.set_markerfacecolor('none')
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.pyplot.stem
matplotlib.axes.Axes.stem
|
c521f6c8d2a6a506e862108e5df226b30f86e0a9a7433b10259d4aa67d4182a4
|
"""
=================
Scatter Star Poly
=================
Create multiple scatter plots with different
star symbols.
"""
import numpy as np
import matplotlib.pyplot as plt
# 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)
plt.subplot(321)
plt.scatter(x, y, s=80, c=z, marker=">")
plt.subplot(322)
plt.scatter(x, y, s=80, c=z, marker=(5, 0))
verts = np.array([[-1, -1], [1, -1], [1, 1], [-1, -1]])
plt.subplot(323)
plt.scatter(x, y, s=80, c=z, marker=verts)
plt.subplot(324)
plt.scatter(x, y, s=80, c=z, marker=(5, 1))
plt.subplot(325)
plt.scatter(x, y, s=80, c=z, marker='+')
plt.subplot(326)
plt.scatter(x, y, s=80, c=z, marker=(5, 2))
plt.show()
|
0b4025139579006ac01b0a284dda15056ae2bcd22f1d8a4281f2b8f5fb99e691
|
"""
==============================
Plotting categorical variables
==============================
How to use categorical variables in Matplotlib.
Many times you want to create a plot that uses categorical variables
in Matplotlib. Matplotlib allows you to pass categorical variables directly to
many plotting functions, which we demonstrate below.
"""
import matplotlib.pyplot as plt
data = {'apples': 10, 'oranges': 15, 'lemons': 5, 'limes': 20}
names = list(data.keys())
values = list(data.values())
fig, axs = plt.subplots(1, 3, figsize=(9, 3), sharey=True)
axs[0].bar(names, values)
axs[1].scatter(names, values)
axs[2].plot(names, values)
fig.suptitle('Categorical Plotting')
###############################################################################
# This works on both axes:
cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing", "washing"]
fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()
plt.show()
|
001bbc21fd16bb19caa467a659c83db28089267dfbdf3c5972bb44d3aa9523cb
|
"""
===================================
Scatter plot with pie chart markers
===================================
This example makes custom 'pie charts' as the markers for a scatter plot.
Thanks to Manuel Metz for the example
"""
import numpy as np
import matplotlib.pyplot as plt
# first define the ratios
r1 = 0.2 # 20%
r2 = r1 + 0.4 # 40%
# define some sizes of the scatter marker
sizes = np.array([60, 80, 120])
# calculate the points of the first pie marker
#
# these are just the origin (0,0) +
# some points on a circle cos,sin
x = [0] + np.cos(np.linspace(0, 2 * np.pi * r1, 10)).tolist()
y = [0] + np.sin(np.linspace(0, 2 * np.pi * r1, 10)).tolist()
xy1 = np.column_stack([x, y])
s1 = np.abs(xy1).max()
x = [0] + np.cos(np.linspace(2 * np.pi * r1, 2 * np.pi * r2, 10)).tolist()
y = [0] + np.sin(np.linspace(2 * np.pi * r1, 2 * np.pi * r2, 10)).tolist()
xy2 = np.column_stack([x, y])
s2 = np.abs(xy2).max()
x = [0] + np.cos(np.linspace(2 * np.pi * r2, 2 * np.pi, 10)).tolist()
y = [0] + np.sin(np.linspace(2 * np.pi * r2, 2 * np.pi, 10)).tolist()
xy3 = np.column_stack([x, y])
s3 = np.abs(xy3).max()
fig, ax = plt.subplots()
ax.scatter(range(3), range(3), marker=xy1,
s=s1 ** 2 * sizes, facecolor='blue')
ax.scatter(range(3), range(3), marker=xy2,
s=s2 ** 2 * sizes, facecolor='green')
ax.scatter(range(3), range(3), marker=xy3,
s=s3 ** 2 * sizes, facecolor='red')
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.axes.Axes.scatter
matplotlib.pyplot.scatter
|
bdf7760489092f47ce07c83b5f21793396c5efe30f1391707027b77b971db273
|
"""
================================
Cross- and Auto-Correlation Demo
================================
Example use of cross-correlation (`xcorr`) and auto-correlation (`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.axhline(0, color='black', lw=2)
ax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2)
ax2.grid(True)
ax2.axhline(0, color='black', lw=2)
plt.show()
|
b63873cdcc3114dd49d230a1b2b8dc2f0c41de948b6bb594daf501ffe272df01
|
"""
===========
Simple Plot
===========
Create a simple plot.
"""
import matplotlib
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()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions and methods is shown in this example:
matplotlib.axes.Axes.plot
matplotlib.pyplot.plot
matplotlib.pyplot.subplots
matplotlib.figure.Figure.savefig
|
dd524e69eb6f972730c5fad22dc977169d301d6d27fa098cc040e7c9122f07e4
|
"""
=====================
Scatter Custom Symbol
=====================
Creating a custom ellipse symbol in scatter plot.
"""
import matplotlib.pyplot as plt
import numpy as np
# unit area ellipse
rx, ry = 3., 1.
area = rx * ry * np.pi
theta = np.arange(0, 2 * np.pi + 0.01, 0.1)
verts = np.column_stack([rx / area * np.cos(theta), ry / area * np.sin(theta)])
x, y, s, c = np.random.rand(4, 30)
s *= 10**2.
fig, ax = plt.subplots()
ax.scatter(x, y, s, c, marker=verts)
plt.show()
|
df136605d6e9ef1dd206c21c437397ed1e7f6d7649a8807d3261fa85951d3010
|
"""
=================
hlines and vlines
=================
This example showcases the functions hlines and vlines.
"""
import matplotlib.pyplot as plt
import numpy as np
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()
|
83997e5344072a448912e1c2cabc02b07b4f3da1d82001913ce2b39007637109
|
"""
====================
EventCollection Demo
====================
Plot two curves, then use EventCollections to mark the locations of the x
and y data points on the respective axes for each curve
"""
import matplotlib.pyplot as plt
from matplotlib.collections import EventCollection
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
# create random data
xdata = np.random.random([2, 10])
# split the data into two parts
xdata1 = xdata[0, :]
xdata2 = xdata[1, :]
# sort the data so it makes clean curves
xdata1.sort()
xdata2.sort()
# create some y data points
ydata1 = xdata1 ** 2
ydata2 = 1 - xdata2 ** 3
# plot the data
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(xdata1, ydata1, color='tab:blue')
ax.plot(xdata2, ydata2, color='tab:orange')
# create the events marking the x data points
xevents1 = EventCollection(xdata1, color='tab:blue', linelength=0.05)
xevents2 = EventCollection(xdata2, color='tab:orange', linelength=0.05)
# create the events marking the y data points
yevents1 = EventCollection(ydata1, color='tab:blue', linelength=0.05,
orientation='vertical')
yevents2 = EventCollection(ydata2, color='tab:orange', linelength=0.05,
orientation='vertical')
# add the events to the axis
ax.add_collection(xevents1)
ax.add_collection(xevents2)
ax.add_collection(yevents1)
ax.add_collection(yevents2)
# set the limits
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.set_title('line plot with data points')
# display the plot
plt.show()
|
c6d15af61bd3968d3aa56875d40cd7f08a3be2abf154646d39a2406600d7c073
|
"""
===============
Errorbar Limits
===============
Illustration of upper and lower limit symbols on errorbars.
"""
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
x = np.arange(10)
y = np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)
plt.errorbar(x, y, yerr=yerr)
plt.errorbar(x, y + 1, yerr=yerr, uplims=True)
plt.errorbar(x, y + 2, yerr=yerr, uplims=True, lolims=True)
upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y + 3, yerr=yerr, uplims=upperlimits, lolims=lowerlimits)
###############################################################################
fig = plt.figure()
x = np.arange(10) / 10
y = (x + 0.1)**2
plt.errorbar(x, y, xerr=0.1, xlolims=True)
y = (x + 0.1)**3
plt.errorbar(x + 0.6, y, xerr=0.1, xuplims=upperlimits, xlolims=lowerlimits)
y = (x + 0.1)**4
plt.errorbar(x + 1.2, y, xerr=0.1, xuplims=True)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.axes.Axes.errorbar
matplotlib.pyplot.errorbar
|
a32330b2c8f73b523b8805c9361e794c9017f0aea8cca3b1653783e217096501
|
'''
==================
Multicolored lines
==================
This example shows how to make a multi-colored line. In this example, the line
is colored based on its derivative.
'''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
dydx = np.cos(0.5 * (x[:-1] + x[1:])) # first derivative
# Create a set of line segments so that we can color them individually
# This creates the points as a 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)
fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
# Create a continuous norm to map from data points to colors
norm = plt.Normalize(dydx.min(), dydx.max())
lc = LineCollection(segments, cmap='viridis', norm=norm)
# Set the values used for colormapping
lc.set_array(dydx)
lc.set_linewidth(2)
line = axs[0].add_collection(lc)
fig.colorbar(line, ax=axs[0])
# Use a boundary norm instead
cmap = ListedColormap(['r', 'g', 'b'])
norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(dydx)
lc.set_linewidth(2)
line = axs[1].add_collection(lc)
fig.colorbar(line, ax=axs[1])
axs[0].set_xlim(x.min(), x.max())
axs[0].set_ylim(-1.1, 1.1)
plt.show()
|
c77163573b729e668413cfb038f4f1326292ba80f5ccc4584e310e8908a8adc9
|
"""
==========
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. See also
`.Line2D.set_linestyle`.
*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 :doc:`property_cycle </tutorials/intermediate/color_cycle>`.
"""
import numpy as np
import matplotlib.pyplot as plt
linestyle_str = [
('solid', 'solid'), # Same as (0, ()) or '-'
('dotted', 'dotted'), # Same as (0, (1, 1)) or '.'
('dashed', 'dashed'), # Same as '--'
('dashdot', 'dashdot')] # Same as '-.'
linestyle_tuple = [
('loosely dotted', (0, (1, 10))),
('dotted', (0, (1, 1))),
('densely dotted', (0, (1, 1))),
('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)
for spine in ax.spines.values():
spine.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, gridspec_kw={'height_ratios': [1, 3]},
figsize=(10, 8))
plot_linestyles(ax0, linestyle_str[::-1], title='Named linestyles')
plot_linestyles(ax1, linestyle_tuple[::-1], title='Parametrized linestyles')
plt.tight_layout()
plt.show()
|
972e8f71eb5e77e127864bbc95d8a259700d412259b7c6dad325ebbf9d2308b4
|
"""
=============
Scatter Demo2
=============
Demo of scatter plot with varying marker colors and sizes.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
# Load a numpy record array from yahoo csv data with fields date, open, close,
# volume, adj_close from the mpl-data/example directory. The record array
# stores the date as an np.datetime64 with a day unit ('D') in the date column.
with cbook.get_sample_data('goog.npz') as datafile:
price_data = np.load(datafile)['price_data'].view(np.recarray)
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()
|
1ea3c492ed34e41cedd56e4e5b81917beb37ca49a96b2a5f6709014c9af3017b
|
"""
=========
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.
The circular markers created with `.pyplot.plot` show the actual data
positions so that it's easier to see the effect of *where*.
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(14)
y = np.sin(x / 2)
plt.step(x, y + 2, label='pre (default)')
plt.plot(x, y + 2, 'C0o', alpha=0.5)
plt.step(x, y + 1, where='mid', label='mid')
plt.plot(x, y + 1, 'C1o', alpha=0.5)
plt.step(x, y, where='post', label='post')
plt.plot(x, y, 'C2o', alpha=0.5)
plt.legend(title='Parameter where:')
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.axes.Axes.step
matplotlib.pyplot.step
|
58b4e412dd4a638bc1198119c25a795d348499225cf10fa055ae7e403016016a
|
"""
=========================
Hatch-filled histograms
=========================
Hatching capabilities for plotting histograms.
"""
import itertools
from collections import OrderedDict
from functools import partial
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from cycler import cycler
def filled_hist(ax, edges, values, bottoms=None, orientation='v',
**kwargs):
"""
Draw a histogram as a stepped patch.
Extra kwargs are passed through to `fill_between`
Parameters
----------
ax : Axes
The axes to plot to
edges : array
A length n+1 array giving the left edges of each bin and the
right edge of the last bin.
values : array
A length n array of bin counts or values
bottoms : scalar or array, optional
A length n array of the bottom of the bars. If None, zero is used.
orientation : {'v', 'h'}
Orientation of the histogram. 'v' (default) has
the bars increasing in the positive y-direction.
Returns
-------
ret : PolyCollection
Artist added to the Axes
"""
print(orientation)
if orientation not in 'hv':
raise ValueError("orientation must be in {{'h', 'v'}} "
"not {o}".format(o=orientation))
kwargs.setdefault('step', 'post')
edges = np.asarray(edges)
values = np.asarray(values)
if len(edges) - 1 != len(values):
raise ValueError('Must provide one more bin edge than value not: '
'len(edges): {lb} len(values): {lv}'.format(
lb=len(edges), lv=len(values)))
if bottoms is None:
bottoms = 0
bottoms = np.broadcast_to(bottoms, values.shape)
values = np.r_[values, values[-1]]
bottoms = np.r_[bottoms, bottoms[-1]]
if orientation == 'h':
return ax.fill_betweenx(edges, values, bottoms,
**kwargs)
elif orientation == 'v':
return ax.fill_between(edges, values, bottoms,
**kwargs)
else:
raise AssertionError("you should never be here")
def stack_hist(ax, stacked_data, sty_cycle, bottoms=None,
hist_func=None, labels=None,
plot_func=None, plot_kwargs=None):
"""
ax : axes.Axes
The axes to add artists too
stacked_data : array or Mapping
A (N, M) shaped array. The first dimension will be iterated over to
compute histograms row-wise
sty_cycle : Cycler or operable of dict
Style to apply to each set
bottoms : array, optional
The initial positions of the bottoms, defaults to 0
hist_func : callable, optional
Must have signature `bin_vals, bin_edges = f(data)`.
`bin_edges` expected to be one longer than `bin_vals`
labels : list of str, optional
The label for each set.
If not given and stacked data is an array defaults to 'default set {n}'
If stacked_data is a mapping, and labels is None, default to the keys
(which may come out in a random order).
If stacked_data is a mapping and labels is given then only
the columns listed by be plotted.
plot_func : callable, optional
Function to call to draw the histogram must have signature:
ret = plot_func(ax, edges, top, bottoms=bottoms,
label=label, **kwargs)
plot_kwargs : dict, optional
Any extra kwargs to pass through to the plotting function. This
will be the same for all calls to the plotting function and will
over-ride the values in cycle.
Returns
-------
arts : dict
Dictionary of artists keyed on their labels
"""
# deal with default binning function
if hist_func is None:
hist_func = np.histogram
# deal with default plotting function
if plot_func is None:
plot_func = filled_hist
# deal with default
if plot_kwargs is None:
plot_kwargs = {}
print(plot_kwargs)
try:
l_keys = stacked_data.keys()
label_data = True
if labels is None:
labels = l_keys
except AttributeError:
label_data = False
if labels is None:
labels = itertools.repeat(None)
if label_data:
loop_iter = enumerate((stacked_data[lab], lab, s)
for lab, s in zip(labels, sty_cycle))
else:
loop_iter = enumerate(zip(stacked_data, labels, sty_cycle))
arts = {}
for j, (data, label, sty) in loop_iter:
if label is None:
label = 'dflt set {n}'.format(n=j)
label = sty.pop('label', label)
vals, edges = hist_func(data)
if bottoms is None:
bottoms = np.zeros_like(vals)
top = bottoms + vals
print(sty)
sty.update(plot_kwargs)
print(sty)
ret = plot_func(ax, edges, top, bottoms=bottoms,
label=label, **sty)
bottoms = top
arts[label] = ret
ax.legend(fontsize=10)
return arts
# set up histogram function to fixed bins
edges = np.linspace(-3, 3, 20, endpoint=True)
hist_func = partial(np.histogram, bins=edges)
# set up style cycles
color_cycle = cycler(facecolor=plt.rcParams['axes.prop_cycle'][:4])
label_cycle = cycler(label=['set {n}'.format(n=n) for n in range(4)])
hatch_cycle = cycler(hatch=['/', '*', '+', '|'])
# Fixing random state for reproducibility
np.random.seed(19680801)
stack_data = np.random.randn(4, 12250)
dict_data = OrderedDict(zip((c['label'] for c in label_cycle), stack_data))
###############################################################################
# Work with plain arrays
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5), tight_layout=True)
arts = stack_hist(ax1, stack_data, color_cycle + label_cycle + hatch_cycle,
hist_func=hist_func)
arts = stack_hist(ax2, stack_data, color_cycle,
hist_func=hist_func,
plot_kwargs=dict(edgecolor='w', orientation='h'))
ax1.set_ylabel('counts')
ax1.set_xlabel('x')
ax2.set_xlabel('counts')
ax2.set_ylabel('x')
###############################################################################
# Work with labeled data
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.5),
tight_layout=True, sharey=True)
arts = stack_hist(ax1, dict_data, color_cycle + hatch_cycle,
hist_func=hist_func)
arts = stack_hist(ax2, dict_data, color_cycle + hatch_cycle,
hist_func=hist_func, labels=['set 0', 'set 3'])
ax1.xaxis.set_major_locator(mticker.MaxNLocator(5))
ax1.set_xlabel('counts')
ax1.set_ylabel('x')
ax2.set_ylabel('x')
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.axes.Axes.fill_betweenx
matplotlib.axes.Axes.fill_between
matplotlib.axis.Axis.set_major_locator
|
a252d0510e90bbaa4f37e4653539e4b3a58232d19e42dde7b2d91a8889315fc9
|
"""
=====================
Marker filling-styles
=====================
Reference for marker fill-styles included with Matplotlib.
Also refer to the
:doc:`/gallery/lines_bars_and_markers/marker_fillstyle_reference`
and :doc:`/gallery/shapes_and_collections/marker_path` examples.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
points = np.ones(5) # Draw 5 points for each line
marker_style = dict(color='tab:blue', linestyle=':', marker='o',
markersize=15, markerfacecoloralt='tab:red')
fig, ax = plt.subplots()
# Plot all fill styles.
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style),
horizontalalignment='center', verticalalignment='center')
ax.plot(y * points, fillstyle=fill_style, **marker_style)
ax.set_axis_off()
ax.set_title('fill style')
plt.show()
|
946a3df849e90662fb2e204e21c6e1be8b783b1e8f2d6f680e052a87561eb9fa
|
"""
==============
Stackplot Demo
==============
How to create stackplots with Matplotlib.
Stackplots are generated by plotting different datasets vertically on
top of one another rather than overlapping with one another. Below we
show some examples to accomplish this with Matplotlib.
"""
import numpy as np
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]
y3 = [1, 3, 5, 7, 9]
y = np.vstack([y1, y2, y3])
labels = ["Fibonacci ", "Evens", "Odds"]
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3, labels=labels)
ax.legend(loc='upper left')
plt.show()
fig, ax = plt.subplots()
ax.stackplot(x, y)
plt.show()
###############################################################################
# Here we show an example of making a streamgraph using stackplot
def layers(n, m):
"""
Return *n* random Gaussian mixtures, each of length *m*.
"""
def bump(a):
x = 1 / (.1 + np.random.random())
y = 2 * np.random.random() - .5
z = 10 / (.1 + np.random.random())
for i in range(m):
w = (i / m - y) * z
a[i] += x * np.exp(-w * w)
a = np.zeros((m, n))
for i in range(n):
for j in range(5):
bump(a[:, i])
return a
d = layers(3, 100)
fig, ax = plt.subplots()
ax.stackplot(range(100), d.T, baseline='wiggle')
plt.show()
|
c91ee63e284430e0253362c94c55f9b1721712294e1a2d3719519c31bcae80d6
|
"""
========================
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, axes = plt.subplots(nrows=3, ncols=2, figsize=(7, 7))
# plot time signal:
axes[0, 0].set_title("Signal")
axes[0, 0].plot(t, s, color='C0')
axes[0, 0].set_xlabel("Time")
axes[0, 0].set_ylabel("Amplitude")
# plot different spectrum types:
axes[1, 0].set_title("Magnitude Spectrum")
axes[1, 0].magnitude_spectrum(s, Fs=Fs, color='C1')
axes[1, 1].set_title("Log. Magnitude Spectrum")
axes[1, 1].magnitude_spectrum(s, Fs=Fs, scale='dB', color='C1')
axes[2, 0].set_title("Phase Spectrum ")
axes[2, 0].phase_spectrum(s, Fs=Fs, color='C2')
axes[2, 1].set_title("Angle Spectrum")
axes[2, 1].angle_spectrum(s, Fs=Fs, color='C2')
axes[0, 1].remove() # don't display empty ax
fig.tight_layout()
plt.show()
|
dde1421bde69f2b4688dfa011e8e688363012ce791e6922e60262625f419c171
|
"""
========
CSD Demo
========
Compute the cross spectral density of two signals
"""
import numpy as np
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(2, 1)
# make a little extra space between the subplots
fig.subplots_adjust(hspace=0.5)
dt = 0.01
t = np.arange(0, 30, dt)
# Fixing random state for reproducibility
np.random.seed(19680801)
nse1 = np.random.randn(len(t)) # white noise 1
nse2 = np.random.randn(len(t)) # white noise 2
r = np.exp(-t / 0.05)
cnse1 = np.convolve(nse1, r, mode='same') * dt # colored noise 1
cnse2 = np.convolve(nse2, r, mode='same') * dt # colored noise 2
# two signals with a coherent part and a random part
s1 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse1
s2 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse2
ax1.plot(t, s1, t, s2)
ax1.set_xlim(0, 5)
ax1.set_xlabel('time')
ax1.set_ylabel('s1 and s2')
ax1.grid(True)
cxy, f = ax2.csd(s1, s2, 256, 1. / dt)
ax2.set_ylabel('CSD (db)')
plt.show()
|
5b72fd6ce6c61bb476f5221d8f229b6d628b5da3c46686177d69af58f2de11f3
|
"""
==========================
Join styles and cap styles
==========================
This example demonstrates the available join styles and cap styles.
Both are used in `.Line2D` and various ``Collections`` from
`matplotlib.collections` as well as some functions that create these, e.g.
`~matplotlib.pyplot.plot`.
Join styles
===========
Join styles define how the connection between two line segments is drawn.
See the respective ``solid_joinstyle``, ``dash_joinstyle`` or ``joinstyle``
parameters.
"""
import numpy as np
import matplotlib.pyplot as plt
def plot_angle(ax, x, y, angle, style):
phi = np.radians(angle)
xx = [x + .5, x, x + .5*np.cos(phi)]
yy = [y, y, y + .5*np.sin(phi)]
ax.plot(xx, yy, lw=12, color='tab:blue', solid_joinstyle=style)
ax.plot(xx, yy, lw=1, color='black')
ax.plot(xx[1], yy[1], 'o', color='tab:red', markersize=3)
fig, ax = plt.subplots(figsize=(8, 6))
ax.set_title('Join style')
for x, style in enumerate(['miter', 'round', 'bevel']):
ax.text(x, 5, style)
for y, angle in enumerate([20, 45, 60, 90, 120]):
plot_angle(ax, x, y, angle, style)
if x == 0:
ax.text(-1.3, y, f'{angle} degrees')
ax.text(1, 4.7, '(default)')
ax.set_xlim(-1.5, 2.75)
ax.set_ylim(-.5, 5.5)
ax.set_axis_off()
plt.show()
#############################################################################
#
# Cap styles
# ==========
#
# Cap styles define how the the end of a line is drawn.
#
# See the respective ``solid_capstyle``, ``dash_capstyle`` or ``capstyle``
# parameters.
fig, ax = plt.subplots(figsize=(8, 2))
ax.set_title('Cap style')
for x, style in enumerate(['butt', 'round', 'projecting']):
ax.text(x+0.25, 1, style, ha='center')
xx = [x, x+0.5]
yy = [0, 0]
ax.plot(xx, yy, lw=12, color='tab:blue', solid_capstyle=style)
ax.plot(xx, yy, lw=1, color='black')
ax.plot(xx, yy, 'o', color='tab:red', markersize=3)
ax.text(2.25, 0.7, '(default)', ha='center')
ax.set_ylim(-.5, 1.5)
ax.set_axis_off()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.axes.Axes.plot
matplotlib.pyplot.plot
|
7db3ed22319db3f5b0829b01b9fabdc94538a3e172bb0e62bb2d63c7702ffec2
|
"""
==============
Scatter Symbol
==============
Scatter plot with clover symbols.
"""
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.arange(0.0, 50.0, 2.0)
y = x ** 1.3 + np.random.rand(*x.shape) * 30.0
s = np.random.rand(*x.shape) * 800 + 500
plt.scatter(x, y, s, c="g", alpha=0.5, marker=r'$\clubsuit$',
label="Luck")
plt.xlabel("Leprechauns")
plt.ylabel("Gold")
plt.legend(loc='upper left')
plt.show()
|
fd349c9dc50374abf7102086c89c818953557bd7aee5e9b403e3a5db875fd473
|
"""
================
Marker Reference
================
Reference for filled-, unfilled- and custom marker types with Matplotlib.
For a list of all markers see the `matplotlib.markers` documentation. Also
refer to the :doc:`/gallery/lines_bars_and_markers/marker_fillstyle_reference`
and :doc:`/gallery/shapes_and_collections/marker_path` examples.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
points = np.ones(3) # Draw 3 points for each line
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontdict={'family': 'monospace'})
marker_style = dict(linestyle=':', color='0.8', markersize=10,
mfc="C0", mec="C0")
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:])
###############################################################################
# Filled and unfilled-marker types
# ================================
#
# Plot all un-filled markers
fig, axes = 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(axes, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot(y * points, marker=marker, **marker_style)
format_axes(ax)
plt.show()
###############################################################################
# Plot all filled markers.
fig, axes = plt.subplots(ncols=2)
for ax, markers in zip(axes, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot(y * points, marker=marker, **marker_style)
format_axes(ax)
fig.suptitle('filled markers', fontsize=14)
plt.show()
###############################################################################
# Custom Markers with MathText
# ============================
#
# Use :doc:`MathText </tutorials/text/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.subplots_adjust(left=0.4)
marker_style.update(mec="None", markersize=15)
markers = ["$1$", r"$\frac{1}{2}$", "$f$", "$\u266B$",
r"$\mathcircled{m}$"]
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 * points, marker=marker, **marker_style)
format_axes(ax)
fig.suptitle('mathtext markers', fontsize=14)
plt.show()
|
14dd1fe55805706efad902ff29500db50f1f59fe6a252547ae484d547c09aee7
|
"""
=========================================
prop_cycle property markevery in rcParams
=========================================
This example demonstrates a working solution to issue #8576, providing full
support of the markevery property for axes.prop_cycle assignments through
rcParams. Makes use of the same list of markevery cases from the
:doc:`markevery demo
</gallery/lines_bars_and_markers/markevery_demo>`.
Renders a plot with shifted-sine curves along each column with
a unique markevery value for each sine curve.
"""
from cycler import cycler
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# Define a list of markevery cases and color cases to plot
cases = [None,
8,
(30, 8),
[16, 24, 30],
[0, -1],
slice(100, 200, 3),
0.1,
0.3,
1.5,
(0.0, 0.1),
(0.45, 0.1)]
colors = ['#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf',
'#1a55FF']
# Configure rcParams axes.prop_cycle to simultaneously cycle cases and colors.
mpl.rcParams['axes.prop_cycle'] = cycler(markevery=cases, color=colors)
# Create data points and offsets
x = np.linspace(0, 2 * np.pi)
offsets = np.linspace(0, 2 * np.pi, 11, endpoint=False)
yy = np.transpose([np.sin(x + phi) for phi in offsets])
# Set the plot curve with markers and a title
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.6, 0.75])
for i in range(len(cases)):
ax.plot(yy[:, i], marker='o', label=str(cases[i]))
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.title('Support for axes.prop_cycle cycler with markevery')
plt.show()
|
f1fcca0d87311203ce3cd122975db0ecf96008b1fba193f220e06ec3db2c8d46
|
"""
==============================
Customizing dashed line styles
==============================
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
:doc:`property_cycle </tutorials/intermediate/color_cycle>`
by passing a list of dash sequences using the keyword *dashes* to the
cycler. This is not shown within this example.
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 500)
y = np.sin(x)
fig, ax = plt.subplots()
# Using set_dashes() to modify dashing of an existing line
line1, = ax.plot(x, y, label='Using set_dashes()')
line1.set_dashes([2, 2, 10, 2]) # 2pt line, 2pt break, 10pt line, 2pt break
# 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')
ax.legend()
plt.show()
|
c2daf5ace13f6ee3d778a3afdcbadc132b239a128e0bf6ff7f70563af022dae1
|
"""
=================
Stacked Bar Graph
=================
This is an example of creating a stacked bar plot with error bars
using `~matplotlib.pyplot.bar`. Note the parameters *yerr* used for
error bars, and *bottom* to stack the women's bars on top of the men's
bars.
"""
import numpy as np
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, menMeans, width, yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
bottom=menMeans, yerr=womenStd)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.show()
|
46e3268ef7a93eb79ca583019c08c08179fa9e63922e219ab081898732586025
|
"""
==============
Markevery Demo
==============
This example demonstrates the various options for showing a marker at a
subset of data points using the ``markevery`` property of a Line2D object.
Integer arguments are fairly intuitive. e.g. ``markevery=5`` will plot every
5th marker starting from the first data point.
Float arguments allow markers to be spaced at approximately equal distances
along the line. The theoretical distance along the line between markers is
determined by multiplying the display-coordinate distance of the axes
bounding-box diagonal by the value of ``markevery``. The data points closest
to the theoretical distances will be shown.
A slice or list/array can also be used with ``markevery`` to specify the
markers to show.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# define a list of markevery cases to plot
cases = [None,
8,
(30, 8),
[16, 24, 30], [0, -1],
slice(100, 200, 3),
0.1, 0.3, 1.5,
(0.0, 0.1), (0.45, 0.1)]
# define the figure size and grid layout properties
figsize = (10, 8)
cols = 3
rows = len(cases) // cols + 1
# define the data for cartesian plots
delta = 0.11
x = np.linspace(0, 10 - 2 * delta, 200) + delta
y = np.sin(x) + 1.0 + delta
def trim_axs(axs, N):
"""little helper to massage the axs list to have correct length..."""
axs = axs.flat
for ax in axs[N:]:
ax.remove()
return axs[:N]
###############################################################################
# Plot each markevery case for linear x and y scales
fig1, axs = plt.subplots(rows, cols, figsize=figsize, constrained_layout=True)
axs = trim_axs(axs, len(cases))
for ax, case in zip(axs, cases):
ax.set_title('markevery=%s' % str(case))
ax.plot(x, y, 'o', ls='-', ms=4, markevery=case)
###############################################################################
# Plot each markevery case for log x and y scales
fig2, axs = plt.subplots(rows, cols, figsize=figsize, constrained_layout=True)
axs = trim_axs(axs, len(cases))
for ax, case in zip(axs, cases):
ax.set_title('markevery=%s' % str(case))
ax.set_xscale('log')
ax.set_yscale('log')
ax.plot(x, y, 'o', ls='-', ms=4, markevery=case)
###############################################################################
# Plot each markevery case for linear x and y scales but zoomed in
# note the behaviour when zoomed in. When a start marker offset is specified
# it is always interpreted with respect to the first data point which might be
# different to the first visible data point.
fig3, axs = plt.subplots(rows, cols, figsize=figsize, constrained_layout=True)
axs = trim_axs(axs, len(cases))
for ax, case in zip(axs, cases):
ax.set_title('markevery=%s' % str(case))
ax.plot(x, y, 'o', ls='-', ms=4, markevery=case)
ax.set_xlim((6, 6.7))
ax.set_ylim((1.1, 1.7))
# define data for polar plots
r = np.linspace(0, 3.0, 200)
theta = 2 * np.pi * r
###############################################################################
# Plot each markevery case for polar plots
fig4, axs = plt.subplots(rows, cols, figsize=figsize,
subplot_kw={'projection': 'polar'}, constrained_layout=True)
axs = trim_axs(axs, len(cases))
for ax, case in zip(axs, cases):
ax.set_title('markevery=%s' % str(case))
ax.plot(theta, r, 'o', ls='-', ms=4, markevery=case)
plt.show()
|
ce6f29cfda94d1de441006638a75e4fb20fa33d8598ad7279997acad84acfd97
|
"""
===========================
Scatter plots 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 numpy as np
np.random.seed(19680801)
import matplotlib.pyplot as plt
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
# :class:`~matplotlib.collections.PathCollection`'s
# :meth:`~.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 :meth:`~.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 :meth:`~.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()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The usage of the following functions and methods is shown in this example:
import matplotlib
matplotlib.axes.Axes.scatter
matplotlib.pyplot.scatter
matplotlib.axes.Axes.legend
matplotlib.pyplot.legend
matplotlib.collections.PathCollection.legend_elements
|
b9505a89ca286452a016c5b418c732cdb369136e1a69cb9c111d98ee6f3009bf
|
"""
===========
Broken Barh
===========
Make a "broken" horizontal bar plot, i.e., one with gaps
"""
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors='tab:blue')
ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),
facecolors=('tab:orange', 'tab:green', 'tab:red'))
ax.set_ylim(5, 35)
ax.set_xlim(0, 200)
ax.set_xlabel('seconds since start')
ax.set_yticks([15, 25])
ax.set_yticklabels(['Bill', 'Jim'])
ax.grid(True)
ax.annotate('race interrupted', (61, 25),
xytext=(0.8, 0.9), textcoords='axes fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
fontsize=16,
horizontalalignment='right', verticalalignment='top')
plt.show()
|
9445747df443b1ad4d3afbf1e5329d3c14bc3b4c3fc5317a351d155300cb0fd5
|
"""
==============================
Filling the area between lines
==============================
This example shows how to use ``fill_between`` to color between lines based on
user-defined logic.
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)
y2 = 1.2 * np.sin(4 * np.pi * x)
###############################################################################
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)
ax1.fill_between(x, 0, y1)
ax1.set_ylabel('between y1 and 0')
ax2.fill_between(x, y1, 1)
ax2.set_ylabel('between y1 and 1')
ax3.fill_between(x, y1, y2)
ax3.set_ylabel('between y1 and y2')
ax3.set_xlabel('x')
###############################################################################
# Now fill between y1 and y2 where a logical condition is met. Note
# this is different than calling
# ``fill_between(x[where], y1[where], y2[where] ...)``
# because of edge effects over multiple contiguous regions.
fig, (ax, ax1) = plt.subplots(2, 1, sharex=True)
ax.plot(x, y1, x, y2, color='black')
ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', interpolate=True)
ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True)
ax.set_title('fill between where')
# Test support for masked arrays.
y2 = np.ma.masked_greater(y2, 1.0)
ax1.plot(x, y1, x, y2, color='black')
ax1.fill_between(x, y1, y2, where=y2 >= y1,
facecolor='green', interpolate=True)
ax1.fill_between(x, y1, y2, where=y2 <= y1,
facecolor='red', interpolate=True)
ax1.set_title('Now regions with y2>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.
###############################################################################
# Use transforms to create axes spans where a certain condition is satisfied:
fig, ax = plt.subplots()
y = np.sin(4 * np.pi * x)
ax.plot(x, y, color='black')
# use data coordinates for the x-axis and the axes coordinates for the y-axis
import matplotlib.transforms as mtransforms
trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)
theta = 0.9
ax.axhline(theta, color='green', lw=2, alpha=0.5)
ax.axhline(-theta, color='red', lw=2, alpha=0.5)
ax.fill_between(x, 0, 1, where=y > theta,
facecolor='green', alpha=0.5, transform=trans)
ax.fill_between(x, 0, 1, where=y < -theta,
facecolor='red', alpha=0.5, transform=trans)
plt.show()
|
15a96a7a8d4c1619d07214db780cc5952ce76fcae2df549d37398c65daf4c3b6
|
"""
============
Gradient Bar
============
"""
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
def gbar(ax, x, y, width=0.5, bottom=0):
X = [[.6, .6], [.7, .7]]
for left, top in zip(x, y):
right = left + width
ax.imshow(X, interpolation='bicubic', cmap=plt.cm.Blues,
extent=(left, right, bottom, top), alpha=1)
xmin, xmax = xlim = 0, 10
ymin, ymax = ylim = 0, 1
fig, ax = plt.subplots()
ax.set(xlim=xlim, ylim=ylim, autoscale_on=False)
X = [[.6, .6], [.7, .7]]
ax.imshow(X, interpolation='bicubic', cmap=plt.cm.copper,
extent=(xmin, xmax, ymin, ymax), alpha=1)
N = 10
x = np.arange(N) + 0.25
y = np.random.rand(N)
gbar(ax, x, y, width=0.7)
ax.set_aspect('auto')
plt.show()
|
92367e9a3df82d12205e290bcb0b9c52ad45b1fc6c81ee858c95bf2df9f6980f
|
"""
========
Nan Test
========
Example: simple line plots with NaNs inserted.
"""
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(2 * 2*np.pi * t)
t[41:60] = np.nan
plt.subplot(2, 1, 1)
plt.plot(t, s, '-', lw=2)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('A sine wave with a gap of NaNs between 0.4 and 0.6')
plt.grid(True)
plt.subplot(2, 1, 2)
t[0] = np.nan
t[-1] = np.nan
plt.plot(t, s, '-', lw=2)
plt.title('Also with NaN in first and last point')
plt.xlabel('time (s)')
plt.ylabel('more nans')
plt.grid(True)
plt.tight_layout()
plt.show()
|
504f06a7cc5848b4102f8248469e42c32db37516e93554c51d443c2f50a322e2
|
"""
================
Using span_where
================
Illustrate some helper functions for shading regions where a logical
mask is True.
See :meth:`matplotlib.collections.BrokenBarHCollection.span_where`
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as collections
t = np.arange(0.0, 2, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = 1.2*np.sin(4*np.pi*t)
fig, ax = plt.subplots()
ax.set_title('using span_where')
ax.plot(t, s1, color='black')
ax.axhline(0, color='black', lw=2)
collection = collections.BrokenBarHCollection.span_where(
t, ymin=0, ymax=1, where=s1 > 0, facecolor='green', alpha=0.5)
ax.add_collection(collection)
collection = collections.BrokenBarHCollection.span_where(
t, ymin=-1, ymax=0, where=s1 < 0, facecolor='red', alpha=0.5)
ax.add_collection(collection)
plt.show()
#############################################################################
#
# ------------
#
# References
# """"""""""
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
import matplotlib
matplotlib.collections.BrokenBarHCollection
matplotlib.collections.BrokenBarHCollection.span_where
matplotlib.axes.Axes.add_collection
matplotlib.axes.Axes.axhline
|
3586242b5a4d5c8090825c40d63ba88ab76abfce41abf178fdae182cff35f8a5
|
"""
==============
Fill plot demo
==============
Demo fill plot.
"""
###############################################################################
# First, the most basic fill plot a user can make with matplotlib:
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 1]
y = [1, 2, 1, 0]
fig, ax = plt.subplots()
ax.fill(x, y)
plt.show()
###############################################################################
# Next, a few more optional features:
#
# * Multiple curves with a single command.
# * Setting the fill color.
# * Setting the opacity (alpha value).
x = np.linspace(0, 1.5 * np.pi, 500)
y1 = np.sin(x)
y2 = np.sin(3 * x)
fig, ax = plt.subplots()
ax.fill(x, y1, 'b', x, y2, 'r', alpha=0.3)
# Outline of the region we've filled in
ax.plot(x, y1, c='b', alpha=0.8)
ax.plot(x, y2, c='r', alpha=0.8)
ax.plot([x[0], x[-1]], [y1[0], y1[-1]], c='b', alpha=0.8)
ax.plot([x[0], x[-1]], [y2[0], y2[-1]], c='r', alpha=0.8)
plt.show()
|
4c62ec58f824d37dba4a8060c5b1d5102e36ea9afa639a85d24bad0c7e81e922
|
"""
========
Psd Demo
========
Plotting Power Spectral Density (PSD) in Matplotlib.
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
import matplotlib.gridspec as gridspec
# 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
plt.subplot(211)
plt.plot(t, s)
plt.subplot(212)
plt.psd(s, 512, 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 = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(2, 3, figure=fig)
ax = fig.add_subplot(gs[0, :])
ax.plot(t, y)
ax.set_xlabel('time [s]')
ax.set_ylabel('signal')
# Plot the PSD with different amounts of zero padding. This uses the entire
# time series at once
ax2 = fig.add_subplot(gs[1, 0])
ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
ax2.psd(y, NFFT=len(t), pad_to=len(t) * 2, Fs=fs)
ax2.psd(y, NFFT=len(t), pad_to=len(t) * 4, Fs=fs)
plt.title('zero padding')
# Plot the PSD with different block sizes, Zero pad to the length of the
# original data sequence.
ax3 = fig.add_subplot(gs[1, 1], sharex=ax2, sharey=ax2)
ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
ax3.psd(y, NFFT=len(t) // 2, pad_to=len(t), Fs=fs)
ax3.psd(y, NFFT=len(t) // 4, pad_to=len(t), Fs=fs)
ax3.set_ylabel('')
plt.title('block size')
# Plot the PSD with different amounts of overlap between blocks
ax4 = fig.add_subplot(gs[1, 2], sharex=ax2, sharey=ax2)
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t), noverlap=0, Fs=fs)
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t),
noverlap=int(0.05 * len(t) / 2.), Fs=fs)
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t),
noverlap=int(0.2 * len(t) / 2.), Fs=fs)
ax4.set_ylabel('')
plt.title('overlap')
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, constrained_layout=True)
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, constrained_layout=True)
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()
|
c01f905caff72b5ac8bfeecc24cd7678154ece6d9215b6d18a9428ea8c4afe91
|
"""
===============
Demo Axes Grid2
===============
Grid of images with shared xaxis and yaxis.
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.colors
def get_demo_image():
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def add_inner_title(ax, title, loc, **kwargs):
from matplotlib.offsetbox import AnchoredText
from matplotlib.patheffects import withStroke
prop = dict(path_effects=[withStroke(foreground='w', linewidth=3)],
size=plt.rcParams['legend.fontsize'])
at = AnchoredText(title, loc=loc, prop=prop,
pad=0., borderpad=0.5,
frameon=False, **kwargs)
ax.add_artist(at)
return at
fig = plt.figure(figsize=(6, 6))
# Prepare images
Z, extent = get_demo_image()
ZS = [Z[i::3, :] for i in range(3)]
extent = extent[0], extent[1]/3., extent[2], extent[3]
# *** Demo 1: colorbar at each axes ***
grid = ImageGrid(fig, 211, # similar to subplot(211)
nrows_ncols=(1, 3),
direction="row",
axes_pad=0.05,
add_all=True,
label_mode="1",
share_all=True,
cbar_location="top",
cbar_mode="each",
cbar_size="7%",
cbar_pad="1%",
)
for ax, z in zip(grid, ZS):
im = ax.imshow(
z, origin="lower", extent=extent, interpolation="nearest")
ax.cax.colorbar(im)
for ax, im_title in zip(grid, ["Image 1", "Image 2", "Image 3"]):
t = add_inner_title(ax, im_title, loc='lower left')
t.patch.set_alpha(0.5)
for ax, z in zip(grid, ZS):
ax.cax.toggle_label(True)
#axis = ax.cax.axis[ax.cax.orientation]
#axis.label.set_text("counts s$^{-1}$")
#axis.label.set_size(10)
#axis.major_ticklabels.set_size(6)
# Changing the colorbar ticks
grid[1].cax.set_xticks([-1, 0, 1])
grid[2].cax.set_xticks([-1, 0, 1])
grid[0].set_xticks([-2, 0])
grid[0].set_yticks([-2, 0, 2])
# *** Demo 2: shared colorbar ***
grid2 = ImageGrid(fig, 212,
nrows_ncols=(1, 3),
direction="row",
axes_pad=0.05,
add_all=True,
label_mode="1",
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="10%",
cbar_pad=0.05,
)
grid2[0].set_xlabel("X")
grid2[0].set_ylabel("Y")
vmax, vmin = np.max(ZS), np.min(ZS)
norm = matplotlib.colors.Normalize(vmax=vmax, vmin=vmin)
for ax, z in zip(grid2, ZS):
im = ax.imshow(z, norm=norm,
origin="lower", extent=extent,
interpolation="nearest")
# With cbar_mode="single", cax attribute of all axes are identical.
ax.cax.colorbar(im)
ax.cax.toggle_label(True)
for ax, im_title in zip(grid2, ["(a)", "(b)", "(c)"]):
t = add_inner_title(ax, im_title, loc='upper left')
t.patch.set_ec("none")
t.patch.set_alpha(0.5)
grid2[0].set_xticks([-2, 0])
grid2[0].set_yticks([-2, 0, 2])
plt.show()
|
f343da3459dd3097491edfd94189fa876915e0b4fa86c8b774711c18d2757a68
|
"""
================
Parasite Simple2
================
"""
import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
obs = [["01_S1", 3.88, 0.14, 1970, 63],
["01_S4", 5.6, 0.82, 1622, 150],
["02_S1", 2.4, 0.54, 1570, 40],
["03_S1", 4.1, 0.62, 2380, 170]]
fig = plt.figure()
ax_kms = SubplotHost(fig, 1, 1, 1, aspect=1.)
# angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc
pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5
aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.)
ax_pm = ax_kms.twin(aux_trans)
ax_pm.set_viewlim_mode("transform")
fig.add_subplot(ax_kms)
for n, ds, dse, w, we in obs:
time = ((2007 + (10. + 4/30.)/12) - 1988.5)
v = ds / time * pm_to_kms
ve = dse / time * pm_to_kms
ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k")
ax_kms.axis["bottom"].set_label("Linear velocity at 2.3 kpc [km/s]")
ax_kms.axis["left"].set_label("FWHM [km/s]")
ax_pm.axis["top"].set_label(r"Proper Motion [$''$/yr]")
ax_pm.axis["top"].label.set_visible(True)
ax_pm.axis["right"].major_ticklabels.set_visible(False)
ax_kms.set_xlim(950, 3700)
ax_kms.set_ylim(950, 3100)
# xlim and ylim of ax_pms will be automatically adjusted.
plt.show()
|
6f2501d707e7bcacbc3b8309e9af4d0aa1d442eb540a442395058d56c77781c8
|
"""
===================
Inset Locator Demo2
===================
This Demo shows how to create a zoomed inset via `~.zoomed_inset_axes`.
In the first subplot an `~.AnchoredSizeBar` shows the zoom effect.
In the second subplot a connection to the region of interest is
created via `~.mark_inset`.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
import numpy as np
def get_demo_image():
from matplotlib.cbook import get_sample_data
import numpy as np
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
fig, (ax, ax2) = plt.subplots(ncols=2, figsize=[6, 3])
# First subplot, showing an inset with a size bar.
ax.set_aspect(1)
axins = zoomed_inset_axes(ax, zoom=0.5, loc='upper right')
# fix the number of ticks on the inset axes
axins.yaxis.get_major_locator().set_params(nbins=7)
axins.xaxis.get_major_locator().set_params(nbins=7)
plt.setp(axins.get_xticklabels(), visible=False)
plt.setp(axins.get_yticklabels(), visible=False)
def add_sizebar(ax, size):
asb = AnchoredSizeBar(ax.transData,
size,
str(size),
loc=8,
pad=0.1, borderpad=0.5, sep=5,
frameon=False)
ax.add_artist(asb)
add_sizebar(ax, 0.5)
add_sizebar(axins, 0.5)
# Second subplot, showing an image with an inset zoom
# and a marked inset
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30 + ny, 30:30 + nx] = Z
# extent = [-3, 4, -4, 3]
ax2.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
axins2 = zoomed_inset_axes(ax2, 6, loc=1) # zoom = 6
axins2.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins2.set_xlim(x1, x2)
axins2.set_ylim(y1, y2)
# fix the number of ticks on the inset axes
axins2.yaxis.get_major_locator().set_params(nbins=7)
axins2.xaxis.get_major_locator().set_params(nbins=7)
plt.setp(axins2.get_xticklabels(), visible=False)
plt.setp(axins2.get_yticklabels(), visible=False)
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax2, axins2, loc1=2, loc2=4, fc="none", ec="0.5")
plt.show()
|
1951fa82b7e3c1ad93cd0a301be052f4a77989465885609d11efa77bae581201
|
"""
======================
Demo Axes Hbox Divider
======================
Hbox Divider to arrange subplots.
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider
import mpl_toolkits.axes_grid1.axes_size as Size
def make_heights_equal(fig, rect, ax1, ax2, pad):
# pad in inches
h1, v1 = Size.AxesX(ax1), Size.AxesY(ax1)
h2, v2 = Size.AxesX(ax2), Size.AxesY(ax2)
pad_v = Size.Scaled(1)
pad_h = Size.Fixed(pad)
my_divider = HBoxDivider(fig, rect,
horizontal=[h1, pad_h, h2],
vertical=[v1, pad_v, v2])
ax1.set_axes_locator(my_divider.new_locator(0))
ax2.set_axes_locator(my_divider.new_locator(2))
if __name__ == "__main__":
arr1 = np.arange(20).reshape((4, 5))
arr2 = np.arange(20).reshape((5, 4))
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(arr1, interpolation="nearest")
ax2.imshow(arr2, interpolation="nearest")
rect = 111 # subplot param for combined axes
make_heights_equal(fig, rect, ax1, ax2, pad=0.5) # pad in inches
for ax in [ax1, ax2]:
ax.locator_params(nbins=4)
# annotate
ax3 = plt.axes([0.5, 0.5, 0.001, 0.001], frameon=False)
ax3.xaxis.set_visible(False)
ax3.yaxis.set_visible(False)
ax3.annotate("Location of two axes are adjusted\n"
"so that they have equal heights\n"
"while maintaining their aspect ratios", (0.5, 0.5),
xycoords="axes fraction", va="center", ha="center",
bbox=dict(boxstyle="round, pad=1", fc="w"))
plt.show()
|
b164551df1c21d8a6617aeef094506870fe6383bcdfca2c3a182dc14abcb61c9
|
"""
===============================
Demo Colorbar with Axes Divider
===============================
The make_axes_locatable function (part of the axes_divider module) takes an
existing axes, creates a divider for it and returns an instance of the
AxesLocator class. The append_axes method of this AxesLocator can then be used
to create a new axes on a given side ("top", "right", "bottom", or "left") of
the original axes. This example uses Axes Divider to add colorbars next to
axes.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
from mpl_toolkits.axes_grid1.colorbar import colorbar
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.subplots_adjust(wspace=0.5)
im1 = ax1.imshow([[1, 2], [3, 4]])
ax1_divider = make_axes_locatable(ax1)
# add an axes to the right of the main axes.
cax1 = ax1_divider.append_axes("right", size="7%", pad="2%")
cb1 = colorbar(im1, cax=cax1)
im2 = ax2.imshow([[1, 2], [3, 4]])
ax2_divider = make_axes_locatable(ax2)
# add an axes above the main axes.
cax2 = ax2_divider.append_axes("top", size="7%", pad="2%")
cb2 = colorbar(im2, cax=cax2, orientation="horizontal")
# change tick position to top. Tick position defaults to bottom and overlaps
# the image.
cax2.xaxis.set_ticks_position("top")
plt.show()
|
3278c80240b532d2efd320f07e2e32a81a8f6acae0a62438818d809958e63674
|
"""
================
Simple ImageGrid
================
Align multiple images using `~mpl_toolkits.axes_grid1.axes_grid.ImageGrid`.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
im1 = np.arange(100).reshape((10, 10))
im2 = im1.T
im3 = np.flipud(im1)
im4 = np.fliplr(im2)
fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(2, 2), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
for ax, im in zip(grid, [im1, im2, im3, im4]):
# Iterating over the grid returns the Axes.
ax.imshow(im)
plt.show()
|
c4a21877460b4e72b71b657020f68213fee7e38aa18c450bce31a3a65a11d5d6
|
"""
================
Simple Axisline4
================
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import numpy as np
ax = host_subplot(111)
xx = np.arange(0, 2*np.pi, 0.01)
ax.plot(xx, np.sin(xx))
ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis
ax2.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi])
ax2.set_xticklabels(["$0$", r"$\frac{1}{2}\pi$",
r"$\pi$", r"$\frac{3}{2}\pi$", r"$2\pi$"])
ax2.axis["right"].major_ticklabels.set_visible(False)
ax2.axis["top"].major_ticklabels.set_visible(True)
plt.show()
|
8b5458d91803ae5661068274c54715ea79d6e6cd9d35b5da390b1fb47ead77fb
|
"""
====================
Demo Fixed Size Axes
====================
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Divider, Size
from mpl_toolkits.axes_grid1.mpl_axes import Axes
def demo_fixed_size_axes():
fig = plt.figure(figsize=(6, 6))
# The first items are for padding and the second items are for the axes.
# sizes are in inch.
h = [Size.Fixed(1.0), Size.Fixed(4.5)]
v = [Size.Fixed(0.7), Size.Fixed(5.)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
# the width and height of the rectangle is ignored.
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
ax.plot([1, 2, 3])
def demo_fixed_pad_axes():
fig = plt.figure(figsize=(6, 6))
# The first & third items are for padding and the second items are for the
# axes. Sizes are in inches.
h = [Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2)]
v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5)]
divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
# the width and height of the rectangle is ignored.
ax = Axes(fig, divider.get_position())
ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
fig.add_axes(ax)
ax.plot([1, 2, 3])
if __name__ == "__main__":
demo_fixed_size_axes()
demo_fixed_pad_axes()
plt.show()
|
5af204af874398796b9d9010371936f9508c1654f021f21e314582c012681d29
|
"""
=====================
Demo Imagegrid Aspect
=====================
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
fig = plt.figure()
grid1 = ImageGrid(fig, 121, (2, 2), axes_pad=0.1,
aspect=True, share_all=True)
for i in [0, 1]:
grid1[i].set_aspect(2)
grid2 = ImageGrid(fig, 122, (2, 2), axes_pad=0.1,
aspect=True, share_all=True)
for i in [1, 3]:
grid2[i].set_aspect(2)
plt.show()
|
5a3608a747eb005d424f0f7278fbb346bfa892c3764a598f2c66527e4f1e1eef
|
"""
==============
Demo Axes Grid
==============
Grid of 2x2 images with single or own colorbar.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
def get_demo_image():
import numpy as np
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def demo_simple_grid(fig):
"""
A grid of 2x2 images with 0.05 inch pad between images and only
the lower-left axes is labeled.
"""
grid = ImageGrid(fig, 141, # similar to subplot(141)
nrows_ncols=(2, 2),
axes_pad=0.05,
label_mode="1",
)
Z, extent = get_demo_image()
for ax in grid:
im = ax.imshow(Z, extent=extent, interpolation="nearest")
# This only affects axes in first column and second row as share_all =
# False.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
def demo_grid_with_single_cbar(fig):
"""
A grid of 2x2 images with a single colorbar
"""
grid = ImageGrid(fig, 142, # similar to subplot(142)
nrows_ncols=(2, 2),
axes_pad=0.0,
share_all=True,
label_mode="L",
cbar_location="top",
cbar_mode="single",
)
Z, extent = get_demo_image()
for ax in grid:
im = ax.imshow(Z, extent=extent, interpolation="nearest")
grid.cbar_axes[0].colorbar(im)
for cax in grid.cbar_axes:
cax.toggle_label(False)
# This affects all axes as share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
def demo_grid_with_each_cbar(fig):
"""
A grid of 2x2 images. Each image has its own colorbar.
"""
grid = ImageGrid(fig, 143, # similar to subplot(143)
nrows_ncols=(2, 2),
axes_pad=0.1,
label_mode="1",
share_all=True,
cbar_location="top",
cbar_mode="each",
cbar_size="7%",
cbar_pad="2%",
)
Z, extent = get_demo_image()
for ax, cax in zip(grid, grid.cbar_axes):
im = ax.imshow(Z, extent=extent, interpolation="nearest")
cax.colorbar(im)
cax.toggle_label(False)
# This affects all axes because we set share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
def demo_grid_with_each_cbar_labelled(fig):
"""
A grid of 2x2 images. Each image has its own colorbar.
"""
grid = ImageGrid(fig, 144, # similar to subplot(144)
nrows_ncols=(2, 2),
axes_pad=(0.45, 0.15),
label_mode="1",
share_all=True,
cbar_location="right",
cbar_mode="each",
cbar_size="7%",
cbar_pad="2%",
)
Z, extent = get_demo_image()
# Use a different colorbar range every time
limits = ((0, 1), (-2, 2), (-1.7, 1.4), (-1.5, 1))
for ax, cax, vlim in zip(grid, grid.cbar_axes, limits):
im = ax.imshow(Z, extent=extent, interpolation="nearest",
vmin=vlim[0], vmax=vlim[1])
cax.colorbar(im)
cax.set_yticks((vlim[0], vlim[1]))
# This affects all axes because we set share_all = True.
grid.axes_llc.set_xticks([-2, 0, 2])
grid.axes_llc.set_yticks([-2, 0, 2])
fig = plt.figure(figsize=(10.5, 2.5))
fig.subplots_adjust(left=0.05, right=0.95)
demo_simple_grid(fig)
demo_grid_with_single_cbar(fig)
demo_grid_with_each_cbar(fig)
demo_grid_with_each_cbar_labelled(fig)
plt.show()
|
39db17de47e6ff98398ff31c25f04dd688f7fcc6fb1bc241744881d4d2a87cf9
|
"""
============
Scatter Hist
============
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Fixing random state for reproducibility
np.random.seed(19680801)
# the random data
x = np.random.randn(1000)
y = np.random.randn(1000)
fig, axScatter = plt.subplots(figsize=(5.5, 5.5))
# the scatter plot:
axScatter.scatter(x, y)
axScatter.set_aspect(1.)
# create new axes on the right and on the top of the current axes
# The first argument of the new_vertical(new_horizontal) method is
# the height (width) of the axes to be created in inches.
divider = make_axes_locatable(axScatter)
axHistx = divider.append_axes("top", 1.2, pad=0.1, sharex=axScatter)
axHisty = divider.append_axes("right", 1.2, pad=0.1, sharey=axScatter)
# make some labels invisible
axHistx.xaxis.set_tick_params(labelbottom=False)
axHisty.yaxis.set_tick_params(labelleft=False)
# now determine nice limits by hand:
binwidth = 0.25
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
lim = (int(xymax/binwidth) + 1)*binwidth
bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')
# the xaxis of axHistx and yaxis of axHisty are shared with axScatter,
# thus there is no need to manually adjust the xlim and ylim of these
# axis.
axHistx.set_yticks([0, 50, 100])
axHisty.set_xticks([0, 50, 100])
plt.show()
|
70d64a0aa94605de4a2078fbdc17e6959d9518515ffdf7c6238491c7c3c0b72e
|
"""
=============
Demo Axes RGB
=============
RGBAxes to show RGB composite images.
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_rgb import make_rgb_axes, RGBAxes
def get_demo_image():
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def get_rgb():
Z, extent = get_demo_image()
Z[Z < 0] = 0.
Z = Z / Z.max()
R = Z[:13, :13]
G = Z[2:, 2:]
B = Z[:13, 2:]
return R, G, B
def make_cube(r, g, b):
ny, nx = r.shape
R = np.zeros([ny, nx, 3], dtype="d")
R[:, :, 0] = r
G = np.zeros_like(R)
G[:, :, 1] = g
B = np.zeros_like(R)
B[:, :, 2] = b
RGB = R + G + B
return R, G, B, RGB
def demo_rgb():
fig, ax = plt.subplots()
ax_r, ax_g, ax_b = make_rgb_axes(ax, pad=0.02)
r, g, b = get_rgb()
im_r, im_g, im_b, im_rgb = make_cube(r, g, b)
kwargs = dict(origin="lower", interpolation="nearest")
ax.imshow(im_rgb, **kwargs)
ax_r.imshow(im_r, **kwargs)
ax_g.imshow(im_g, **kwargs)
ax_b.imshow(im_b, **kwargs)
def demo_rgb2():
fig = plt.figure()
ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8], pad=0.0)
r, g, b = get_rgb()
kwargs = dict(origin="lower", interpolation="nearest")
ax.imshow_rgb(r, g, b, **kwargs)
ax.RGB.set_xlim(0., 9.5)
ax.RGB.set_ylim(0.9, 10.6)
for ax1 in [ax.RGB, ax.R, ax.G, ax.B]:
ax1.tick_params(axis='both', direction='in')
for sp1 in ax1.spines.values():
sp1.set_color("w")
for tick in ax1.xaxis.get_major_ticks() + ax1.yaxis.get_major_ticks():
tick.tick1line.set_markeredgecolor("w")
tick.tick2line.set_markeredgecolor("w")
return ax
demo_rgb()
demo_rgb2()
plt.show()
|
5aa3b713a97814570174a516125d666a32707d5292a730435b1beff9d2922b20
|
"""
===============
Parasite Simple
===============
"""
from mpl_toolkits.axes_grid1 import host_subplot
import matplotlib.pyplot as plt
host = host_subplot(111)
par = host.twinx()
host.set_xlabel("Distance")
host.set_ylabel("Density")
par.set_ylabel("Temperature")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature")
leg = plt.legend()
host.yaxis.get_label().set_color(p1.get_color())
leg.texts[0].set_color(p1.get_color())
par.yaxis.get_label().set_color(p2.get_color())
leg.texts[1].set_color(p2.get_color())
plt.show()
|
18960a281e5102ea3a9d9abae4cfb82ca27d985ac2ae5e43d080b6f3cc18b1e4
|
"""
===========================
Demo Colorbar of Inset Axes
===========================
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes, zoomed_inset_axes
from mpl_toolkits.axes_grid1.colorbar import colorbar
def get_demo_image():
from matplotlib.cbook import get_sample_data
import numpy as np
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
fig, ax = plt.subplots(figsize=[5, 4])
Z, extent = get_demo_image()
ax.set(aspect=1,
xlim=(-15, 15),
ylim=(-20, 5))
axins = zoomed_inset_axes(ax, zoom=2, loc='upper left')
im = axins.imshow(Z, extent=extent, interpolation="nearest",
origin="lower")
plt.xticks(visible=False)
plt.yticks(visible=False)
# colorbar
cax = inset_axes(axins,
width="5%", # width = 10% of parent_bbox width
height="100%", # height : 50%
loc='lower left',
bbox_to_anchor=(1.05, 0., 1, 1),
bbox_transform=axins.transAxes,
borderpad=0,
)
colorbar(im, cax=cax)
plt.show()
|
437c4766750e7fd4341bcac06ffffb070f9b8c16b97095b994bd313777563ff8
|
"""
===================================
Make Room For Ylabel Using Axesgrid
===================================
"""
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable
if __name__ == "__main__":
import matplotlib.pyplot as plt
def ex1():
plt.figure(1)
ax = plt.axes([0, 0, 1, 1])
#ax = plt.subplot(111)
ax.set_yticks([0.5])
ax.set_yticklabels(["very long label"])
make_axes_area_auto_adjustable(ax)
def ex2():
plt.figure(2)
ax1 = plt.axes([0, 0, 1, 0.5])
ax2 = plt.axes([0, 0.5, 1, 0.5])
ax1.set_yticks([0.5])
ax1.set_yticklabels(["very long label"])
ax1.set_ylabel("Y label")
ax2.set_title("Title")
make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2])
make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2])
def ex3():
fig = plt.figure(3)
ax1 = plt.axes([0, 0, 1, 1])
divider = make_axes_locatable(ax1)
ax2 = divider.new_horizontal("100%", pad=0.3, sharey=ax1)
ax2.tick_params(labelleft=False)
fig.add_axes(ax2)
divider.add_auto_adjustable_area(use_axes=[ax1], pad=0.1,
adjust_dirs=["left"])
divider.add_auto_adjustable_area(use_axes=[ax2], pad=0.1,
adjust_dirs=["right"])
divider.add_auto_adjustable_area(use_axes=[ax1, ax2], pad=0.1,
adjust_dirs=["top", "bottom"])
ax1.set_yticks([0.5])
ax1.set_yticklabels(["very long label"])
ax2.set_title("Title")
ax2.set_xlabel("X - Label")
ex1()
ex2()
ex3()
plt.show()
|
8d11844dfb5e70ee6b22bd89546bfc628816d26d89817dc6eae4511872ef58b4
|
"""
=============================
Demo Anchored Direction Arrow
=============================
"""
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDirectionArrows
import matplotlib.font_manager as fm
fig, ax = plt.subplots()
ax.imshow(np.random.random((10, 10)))
# Simple example
simple_arrow = AnchoredDirectionArrows(ax.transAxes, 'X', 'Y')
ax.add_artist(simple_arrow)
# High contrast arrow
high_contrast_part_1 = AnchoredDirectionArrows(
ax.transAxes,
'111', r'11$\overline{2}$',
loc='upper right',
arrow_props={'ec': 'w', 'fc': 'none', 'alpha': 1,
'lw': 2}
)
ax.add_artist(high_contrast_part_1)
high_contrast_part_2 = AnchoredDirectionArrows(
ax.transAxes,
'111', r'11$\overline{2}$',
loc='upper right',
arrow_props={'ec': 'none', 'fc': 'k'},
text_props={'ec': 'w', 'fc': 'k', 'lw': 0.4}
)
ax.add_artist(high_contrast_part_2)
# Rotated arrow
fontprops = fm.FontProperties(family='serif')
roatated_arrow = AnchoredDirectionArrows(
ax.transAxes,
'30', '120',
loc='center',
color='w',
angle=30,
fontproperties=fontprops
)
ax.add_artist(roatated_arrow)
# Altering arrow directions
a1 = AnchoredDirectionArrows(
ax.transAxes, 'A', 'B', loc='lower center',
length=-0.15,
sep_x=0.03, sep_y=0.03,
color='r'
)
ax.add_artist(a1)
a2 = AnchoredDirectionArrows(
ax.transAxes, 'A', ' B', loc='lower left',
aspect_ratio=-1,
sep_x=0.01, sep_y=-0.02,
color='orange'
)
ax.add_artist(a2)
a3 = AnchoredDirectionArrows(
ax.transAxes, ' A', 'B', loc='lower right',
length=-0.15,
aspect_ratio=-1,
sep_y=-0.1, sep_x=0.04,
color='cyan'
)
ax.add_artist(a3)
plt.show()
|
9c474df6c058a717ca86879b16a0df05a673431dbe006d39b9a79a1533475a55
|
"""
=======================
Simple Anchored Artists
=======================
This example illustrates the use of the anchored helper classes found in
:py:mod:`~matplotlib.offsetbox` and in the :ref:`toolkit_axesgrid1-index`.
An implementation of a similar figure, but without use of the toolkit,
can be found in :doc:`/gallery/misc/anchored_artists`.
"""
import matplotlib.pyplot as plt
def draw_text(ax):
"""
Draw two text-boxes, anchored by different corners to the upper-left
corner of the figure.
"""
from matplotlib.offsetbox import AnchoredText
at = AnchoredText("Figure 1a",
loc='upper left', prop=dict(size=8), frameon=True,
)
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at)
at2 = AnchoredText("Figure 1(b)",
loc='lower left', prop=dict(size=8), frameon=True,
bbox_to_anchor=(0., 1.),
bbox_transform=ax.transAxes
)
at2.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at2)
def draw_circle(ax):
"""
Draw a circle in axis coordinates
"""
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea
from matplotlib.patches import Circle
ada = AnchoredDrawingArea(20, 20, 0, 0,
loc='upper right', pad=0., frameon=False)
p = Circle((10, 10), 10)
ada.da.add_artist(p)
ax.add_artist(ada)
def draw_ellipse(ax):
"""
Draw an ellipse of width=0.1, height=0.15 in data coordinates
"""
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredEllipse
ae = AnchoredEllipse(ax.transData, width=0.1, height=0.15, angle=0.,
loc='lower left', pad=0.5, borderpad=0.4,
frameon=True)
ax.add_artist(ae)
def draw_sizebar(ax):
"""
Draw a horizontal bar with length of 0.1 in data coordinates,
with a fixed label underneath.
"""
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
asb = AnchoredSizeBar(ax.transData,
0.1,
r"1$^{\prime}$",
loc='lower center',
pad=0.1, borderpad=0.5, sep=5,
frameon=False)
ax.add_artist(asb)
ax = plt.gca()
ax.set_aspect(1.)
draw_text(ax)
draw_circle(ax)
draw_ellipse(ax)
draw_sizebar(ax)
plt.show()
|
ec57464cb11772869000e789b275d154f428c037e19f2054b51c672ffbefc154
|
"""
=====================
Simple Axes Divider 3
=====================
"""
import mpl_toolkits.axes_grid1.axes_size as Size
from mpl_toolkits.axes_grid1 import Divider
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(5.5, 4))
# the rect parameter will be ignore as we will set axes_locator
rect = (0.1, 0.1, 0.8, 0.8)
ax = [fig.add_axes(rect, label="%d" % i) for i in range(4)]
horiz = [Size.AxesX(ax[0]), Size.Fixed(.5), Size.AxesX(ax[1])]
vert = [Size.AxesY(ax[0]), Size.Fixed(.5), Size.AxesY(ax[2])]
# divide the axes rectangle into grid whose size is specified by horiz * vert
divider = Divider(fig, rect, horiz, vert, aspect=False)
ax[0].set_axes_locator(divider.new_locator(nx=0, ny=0))
ax[1].set_axes_locator(divider.new_locator(nx=2, ny=0))
ax[2].set_axes_locator(divider.new_locator(nx=0, ny=2))
ax[3].set_axes_locator(divider.new_locator(nx=2, ny=2))
ax[0].set_xlim(0, 2)
ax[1].set_xlim(0, 1)
ax[0].set_ylim(0, 1)
ax[2].set_ylim(0, 2)
divider.set_aspect(1.)
for ax1 in ax:
ax1.tick_params(labelbottom=False, labelleft=False)
plt.show()
|
e3db50d345d369bca4015893a493784b3e7dcd02eb2ee5c6c359277787a89781
|
"""
==================
Simple ImageGrid 2
==================
Align multiple images of different sizes using
`~mpl_toolkits.axes_grid1.axes_grid.ImageGrid`.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
def get_demo_image():
import numpy as np
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
fig = plt.figure(figsize=(5.5, 3.5))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(1, 3),
axes_pad=0.1,
add_all=True,
label_mode="L",
)
Z, extent = get_demo_image() # demo image
im1 = Z
im2 = Z[:, :10]
im3 = Z[:, 10:]
vmin, vmax = Z.min(), Z.max()
for ax, im in zip(grid, [im1, im2, im3]):
ax.imshow(im, origin="lower", vmin=vmin, vmax=vmax,
interpolation="nearest")
plt.show()
|
baf25f9a484dc43de5eadf358e78042b1684763661d0be39dce2dcfe3a4de9b8
|
"""
==========
Simple RGB
==========
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes
def get_demo_image():
import numpy as np
from matplotlib.cbook import get_sample_data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
def get_rgb():
Z, extent = get_demo_image()
Z[Z < 0] = 0.
Z = Z / Z.max()
R = Z[:13, :13]
G = Z[2:, 2:]
B = Z[:13, 2:]
return R, G, B
fig = plt.figure()
ax = RGBAxes(fig, [0.1, 0.1, 0.8, 0.8])
r, g, b = get_rgb()
kwargs = dict(origin="lower", interpolation="nearest")
ax.imshow_rgb(r, g, b, **kwargs)
ax.RGB.set_xlim(0., 9.5)
ax.RGB.set_ylim(0.9, 10.6)
plt.show()
|
acf2f710bdbc1a37291ebac18bef11b5776e60a0151f793ebb1f8d2a8ca577cd
|
"""
===============
Simple Colorbar
===============
"""
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
ax = plt.subplot(111)
im = ax.imshow(np.arange(100).reshape((10, 10)))
# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax)
|
e97ef6b43b3ff67b9a59bb500a3f2feb65e4c3de0874e37b2031f70f9402730c
|
"""
==================
Inset Locator Demo
==================
"""
###############################################################################
# The `.inset_locator`'s `~.inset_locator.inset_axes` allows
# easily placing insets in the corners of the axes by specifying a width and
# height and optionally a location (loc) that accepts locations as codes,
# similar to `~matplotlib.axes.Axes.legend`.
# By default, the inset is offset by some points from the axes,
# controlled via the `borderpad` parameter.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, (ax, ax2) = plt.subplots(1, 2, figsize=[5.5, 2.8])
# Create inset of width 1.3 inches and height 0.9 inches
# at the default upper right location
axins = inset_axes(ax, width=1.3, height=0.9)
# Create inset of width 30% and height 40% of the parent axes' bounding box
# at the lower left corner (loc=3)
axins2 = inset_axes(ax, width="30%", height="40%", loc=3)
# Create inset of mixed specifications in the second subplot;
# width is 30% of parent axes' bounding box and
# height is 1 inch at the upper left corner (loc=2)
axins3 = inset_axes(ax2, width="30%", height=1., loc=2)
# Create an inset in the lower right corner (loc=4) with borderpad=1, i.e.
# 10 points padding (as 10pt is the default fontsize) to the parent axes
axins4 = inset_axes(ax2, width="20%", height="20%", loc=4, borderpad=1)
# Turn ticklabels of insets off
for axi in [axins, axins2, axins3, axins4]:
axi.tick_params(labelleft=False, labelbottom=False)
plt.show()
###############################################################################
# The arguments `bbox_to_anchor` and `bbox_transfrom` can be used for a more
# fine grained control over the inset position and size or even to position
# the inset at completely arbitrary positions.
# The `bbox_to_anchor` sets the bounding box in coordinates according to the
# `bbox_transform`.
#
fig = plt.figure(figsize=[5.5, 2.8])
ax = fig.add_subplot(121)
# We use the axes transform as bbox_transform. Therefore the bounding box
# needs to be specified in axes coordinates ((0,0) is the lower left corner
# of the axes, (1,1) is the upper right corner).
# The bounding box (.2, .4, .6, .5) starts at (.2,.4) and ranges to (.8,.9)
# in those coordinates.
# Inside of this bounding box an inset of half the bounding box' width and
# three quarters of the bounding box' height is created. The lower left corner
# of the inset is aligned to the lower left corner of the bounding box (loc=3).
# The inset is then offset by the default 0.5 in units of the font size.
axins = inset_axes(ax, width="50%", height="75%",
bbox_to_anchor=(.2, .4, .6, .5),
bbox_transform=ax.transAxes, loc=3)
# For visualization purposes we mark the bounding box by a rectangle
ax.add_patch(plt.Rectangle((.2, .4), .6, .5, ls="--", ec="c", fc="None",
transform=ax.transAxes))
# We set the axis limits to something other than the default, in order to not
# distract from the fact that axes coordinates are used here.
ax.axis([0, 10, 0, 10])
# Note how the two following insets are created at the same positions, one by
# use of the default parent axes' bbox and the other via a bbox in axes
# coordinates and the respective transform.
ax2 = fig.add_subplot(222)
axins2 = inset_axes(ax2, width="30%", height="50%")
ax3 = fig.add_subplot(224)
axins3 = inset_axes(ax3, width="100%", height="100%",
bbox_to_anchor=(.7, .5, .3, .5),
bbox_transform=ax3.transAxes)
# For visualization purposes we mark the bounding box by a rectangle
ax2.add_patch(plt.Rectangle((0, 0), 1, 1, ls="--", lw=2, ec="c", fc="None"))
ax3.add_patch(plt.Rectangle((.7, .5), .3, .5, ls="--", lw=2,
ec="c", fc="None"))
# Turn ticklabels off
for axi in [axins2, axins3, ax2, ax3]:
axi.tick_params(labelleft=False, labelbottom=False)
plt.show()
###############################################################################
# In the above the axes transform together with 4-tuple bounding boxes has been
# used as it mostly is useful to specify an inset relative to the axes it is
# an inset to. However other use cases are equally possible. The following
# example examines some of those.
#
fig = plt.figure(figsize=[5.5, 2.8])
ax = fig.add_subplot(131)
# Create an inset outside the axes
axins = inset_axes(ax, width="100%", height="100%",
bbox_to_anchor=(1.05, .6, .5, .4),
bbox_transform=ax.transAxes, loc=2, borderpad=0)
axins.tick_params(left=False, right=True, labelleft=False, labelright=True)
# Create an inset with a 2-tuple bounding box. Note that this creates a
# bbox without extent. This hence only makes sense when specifying
# width and height in absolute units (inches).
axins2 = inset_axes(ax, width=0.5, height=0.4,
bbox_to_anchor=(0.33, 0.25),
bbox_transform=ax.transAxes, loc=3, borderpad=0)
ax2 = fig.add_subplot(133)
ax2.set_xscale("log")
ax2.axis([1e-6, 1e6, -2, 6])
# Create inset in data coordinates using ax.transData as transform
axins3 = inset_axes(ax2, width="100%", height="100%",
bbox_to_anchor=(1e-2, 2, 1e3, 3),
bbox_transform=ax2.transData, loc=2, borderpad=0)
# Create an inset horizontally centered in figure coordinates and vertically
# bound to line up with the axes.
from matplotlib.transforms import blended_transform_factory
transform = blended_transform_factory(fig.transFigure, ax2.transAxes)
axins4 = inset_axes(ax2, width="16%", height="34%",
bbox_to_anchor=(0, 0, 1, 1),
bbox_transform=transform, loc=8, borderpad=0)
plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.