matplotlib & pandas

This commit is contained in:
estomm
2020-09-26 22:03:11 +08:00
parent 73cc328c81
commit d31be4f219
599 changed files with 99925 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
# Agg缓冲区
使用后端AGG以RGB字符串的形式访问地物画布然后将其转换为数组并将其传递给Pillow进行渲染。
![Agg缓冲区](https://matplotlib.org/_images/sphx_glr_agg_buffer_001.png)
```python
import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
canvas = plt.get_current_fig_manager().canvas
agg = canvas.switch_backends(FigureCanvasAgg)
agg.draw()
s, (width, height) = agg.print_to_buffer()
# Convert to a NumPy array.
X = np.fromstring(s, np.uint8).reshape((height, width, 4))
# Pass off to PIL.
from PIL import Image
im = Image.frombytes("RGBA", (width, height), s)
# Uncomment this line to display the image using ImageMagick's `display` tool.
# im.show()
```
## 下载这个示例
- [下载python源码: agg_buffer.py](https://matplotlib.org/_downloads/agg_buffer.py)
- [下载Jupyter notebook: agg_buffer.ipynb](https://matplotlib.org/_downloads/agg_buffer.ipynb)

View File

@@ -0,0 +1,32 @@
# Agg缓冲区转换数组
将渲染图形转换为其图像(NumPy数组)表示形式。
![Agg缓冲区转换数组示例](https://matplotlib.org/_images/sphx_glr_agg_buffer_to_array_001.png)
![Agg缓冲区转换数组示例2](https://matplotlib.org/_images/sphx_glr_agg_buffer_to_array_002.png)
```python
import matplotlib.pyplot as plt
import numpy as np
# make an agg figure
fig, ax = plt.subplots()
ax.plot([1, 2, 3])
ax.set_title('a simple figure')
fig.canvas.draw()
# grab the pixel buffer and dump it into a numpy array
X = np.array(fig.canvas.renderer._renderer)
# now display the array X as an Axes in a new figure
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, frameon=False)
ax2.imshow(X)
plt.show()
```
## 下载这个示例
- [下载python源码: agg_buffer_to_array.py](https://matplotlib.org/_downloads/agg_buffer_to_array.py)
- [下载Jupyter notebook: agg_buffer_to_array.ipynb](https://matplotlib.org/_downloads/agg_buffer_to_array.ipynb)

View File

@@ -0,0 +1,128 @@
# 锚定艺术家对象
这个使用没有辅助类的锚定对象的示例在[Matplotlib axes_grid1 Toolkit](https://matplotlib.org/api/toolkits/axes_grid1.html#toolkit-axesgrid1-index)中找到。此版本的图与Simple [Anchored Artists](https://matplotlib.org/gallery/axes_grid1/simple_anchored_artists.html)中的版本类似但它仅使用matplotlib命名空间实现没有其他工具包的帮助。
![锚定艺术家对象示例](https://matplotlib.org/_images/sphx_glr_anchored_artists_001.png)
```python
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle, Ellipse
from matplotlib.offsetbox import (
AnchoredOffsetbox, AuxTransformBox, DrawingArea, TextArea, VPacker)
class AnchoredText(AnchoredOffsetbox):
def __init__(self, s, loc, pad=0.4, borderpad=0.5,
prop=None, frameon=True):
self.txt = TextArea(s, minimumdescent=False)
super().__init__(loc, pad=pad, borderpad=borderpad,
child=self.txt, prop=prop, frameon=frameon)
def draw_text(ax):
"""
Draw a text-box anchored to the upper-left corner of the figure.
"""
at = AnchoredText("Figure 1a", loc='upper left', frameon=True)
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at)
class AnchoredDrawingArea(AnchoredOffsetbox):
def __init__(self, width, height, xdescent, ydescent,
loc, pad=0.4, borderpad=0.5, prop=None, frameon=True):
self.da = DrawingArea(width, height, xdescent, ydescent)
super().__init__(loc, pad=pad, borderpad=borderpad,
child=self.da, prop=None, frameon=frameon)
def draw_circle(ax):
"""
Draw a circle in axis coordinates
"""
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)
class AnchoredEllipse(AnchoredOffsetbox):
def __init__(self, transform, width, height, angle, loc,
pad=0.1, borderpad=0.1, prop=None, frameon=True):
"""
Draw an ellipse the size in data coordinate of the give axes.
pad, borderpad in fraction of the legend font size (or prop)
"""
self._box = AuxTransformBox(transform)
self.ellipse = Ellipse((0, 0), width, height, angle)
self._box.add_artist(self.ellipse)
super().__init__(loc, pad=pad, borderpad=borderpad,
child=self._box, prop=prop, frameon=frameon)
def draw_ellipse(ax):
"""
Draw an ellipse of width=0.1, height=0.15 in data coordinates
"""
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)
class AnchoredSizeBar(AnchoredOffsetbox):
def __init__(self, transform, size, label, loc,
pad=0.1, borderpad=0.1, sep=2, prop=None, frameon=True):
"""
Draw a horizontal bar with the size in data coordinate of the given
axes. A label will be drawn underneath (center-aligned).
pad, borderpad in fraction of the legend font size (or prop)
sep in points.
"""
self.size_bar = AuxTransformBox(transform)
self.size_bar.add_artist(Rectangle((0, 0), size, 0, ec="black", lw=1.0))
self.txt_label = TextArea(label, minimumdescent=False)
self._box = VPacker(children=[self.size_bar, self.txt_label],
align="center",
pad=0, sep=sep)
super().__init__(loc, pad=pad, borderpad=borderpad,
child=self._box, prop=prop, frameon=frameon)
def draw_sizebar(ax):
"""
Draw a horizontal bar with length of 0.1 in data coordinates,
with a fixed label underneath.
"""
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()
```
## 下载这个示例
- [下载python源码: anchored_artists.py](https://matplotlib.org/_downloads/anchored_artists.py)
- [下载Jupyter notebook: anchored_artists.ipynb](https://matplotlib.org/_downloads/anchored_artists.ipynb)

View File

@@ -0,0 +1,40 @@
# 改变与盒子相交的线条的颜色
与矩形相交的线条用红色着色而其他线条用蓝色线条留下。此示例展示了intersect_bbox函数。
![改变与盒子相交的线条的颜色示例](https://matplotlib.org/_images/sphx_glr_bbox_intersect_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.path import Path
# Fixing random state for reproducibility
np.random.seed(19680801)
left, bottom, width, height = (-1, -1, 2, 2)
rect = plt.Rectangle((left, bottom), width, height, facecolor="#aaaaaa")
fig, ax = plt.subplots()
ax.add_patch(rect)
bbox = Bbox.from_bounds(left, bottom, width, height)
for i in range(12):
vertices = (np.random.random((2, 2)) - 0.5) * 6.0
path = Path(vertices)
if path.intersects_bbox(bbox):
color = 'r'
else:
color = 'b'
ax.plot(vertices[:, 0], vertices[:, 1], color=color)
plt.show()
```
## 下载这个示例
- [下载python源码: bbox_intersect.py](https://matplotlib.org/_downloads/bbox_intersect.py)
- [下载Jupyter notebook: bbox_intersect.ipynb](https://matplotlib.org/_downloads/bbox_intersect.ipynb)

View File

@@ -0,0 +1,65 @@
# Contour手册
使用ContourSet显示自己的轮廓线和多边形的示例。
```python
import matplotlib.pyplot as plt
from matplotlib.contour import ContourSet
import matplotlib.cm as cm
```
每个级别的轮廓线是多边形的列表/元组。
```python
lines0 = [[[0, 0], [0, 4]]]
lines1 = [[[2, 0], [1, 2], [1, 3]]]
lines2 = [[[3, 0], [3, 2]], [[3, 3], [3, 4]]] # Note two lines.
```
两个级别之间的填充等高线也是多边形的列表/元组。点可以顺时针或逆时针排列。
```python
filled01 = [[[0, 0], [0, 4], [1, 3], [1, 2], [2, 0]]]
filled12 = [[[2, 0], [3, 0], [3, 2], [1, 3], [1, 2]], # Note two polygons.
[[1, 4], [3, 4], [3, 3]]]
```
```python
plt.figure()
# Filled contours using filled=True.
cs = ContourSet(plt.gca(), [0, 1, 2], [filled01, filled12], filled=True, cmap=cm.bone)
cbar = plt.colorbar(cs)
# Contour lines (non-filled).
lines = ContourSet(plt.gca(), [0, 1, 2], [lines0, lines1, lines2], cmap=cm.cool,
linewidths=3)
cbar.add_lines(lines)
plt.axis([-0.5, 3.5, -0.5, 4.5])
plt.title('User-specified contours')
```
![Contour手册示例](https://matplotlib.org/_images/sphx_glr_contour_manual_001.png)
可以在单个多边形顶点列表中指定多个填充轮廓线以及Path类中描述的顶点种类代码类型列表。 这对于带孔的多边形特别有用。 代码类型1是MOVETO2是LINETO。
```python
plt.figure()
filled01 = [[[0, 0], [3, 0], [3, 3], [0, 3], [1, 1], [1, 2], [2, 2], [2, 1]]]
kinds01 = [[1, 2, 2, 2, 1, 2, 2, 2]]
cs = ContourSet(plt.gca(), [0, 1], [filled01], [kinds01], filled=True)
cbar = plt.colorbar(cs)
plt.axis([-0.5, 3.5, -0.5, 3.5])
plt.title('User specified filled contours with holes')
plt.show()
```
![Contour手册示例2](https://matplotlib.org/_images/sphx_glr_contour_manual_002.png)
## 下载这个示例
- [下载python源码: contour_manual.py](https://matplotlib.org/_downloads/contour_manual.py)
- [下载Jupyter notebook: contour_manual.ipynb](https://matplotlib.org/_downloads/contour_manual.ipynb)

View File

@@ -0,0 +1,32 @@
# 坐标报告
覆盖coords的默认报告。
![坐标报告示例](https://matplotlib.org/_images/sphx_glr_coords_report_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
def millions(x):
return '$%1.1fM' % (x*1e-6)
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.rand(20)
y = 1e7*np.random.rand(20)
fig, ax = plt.subplots()
ax.fmt_ydata = millions
plt.plot(x, y, 'o')
plt.show()
```
## 下载这个示例
- [下载python源码: coords_report.py](https://matplotlib.org/_downloads/coords_report.py)
- [下载Jupyter notebook: coords_report.ipynb](https://matplotlib.org/_downloads/coords_report.ipynb)

View File

@@ -0,0 +1,87 @@
# 光标演示
此示例显示如何使用matplotlib提供数据游标。 它使用matplotlib来绘制光标并且可能很慢因为这需要在每次鼠标移动时重新绘制图形。
使用本机GUI绘图可以更快地进行镜像就像在wxcursor_demo.py中一样。
mpldatacursor和mplcursors第三方包可用于实现类似的效果。参看这个
https://github.com/joferkington/mpldatacursor https://github.com/anntzer/mplcursors
```python
import matplotlib.pyplot as plt
import numpy as np
class Cursor(object):
def __init__(self, ax):
self.ax = ax
self.lx = ax.axhline(color='k') # the horiz line
self.ly = ax.axvline(color='k') # the vert line
# text location in axes coords
self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
# update the line positions
self.lx.set_ydata(y)
self.ly.set_xdata(x)
self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
plt.draw()
class SnaptoCursor(object):
"""
Like Cursor but the crosshair snaps to the nearest x,y point
For simplicity, I'm assuming x is sorted
"""
def __init__(self, ax, x, y):
self.ax = ax
self.lx = ax.axhline(color='k') # the horiz line
self.ly = ax.axvline(color='k') # the vert line
self.x = x
self.y = y
# text location in axes coords
self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
indx = min(np.searchsorted(self.x, [x])[0], len(self.x) - 1)
x = self.x[indx]
y = self.y[indx]
# update the line positions
self.lx.set_ydata(y)
self.ly.set_xdata(x)
self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
print('x=%1.2f, y=%1.2f' % (x, y))
plt.draw()
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * 2 * np.pi * t)
fig, ax = plt.subplots()
# cursor = Cursor(ax)
cursor = SnaptoCursor(ax, t, s)
plt.connect('motion_notify_event', cursor.mouse_move)
ax.plot(t, s, 'o')
plt.axis([0, 1, -1, 1])
plt.show()
```
## 下载这个示例
- [下载python源码: cursor_demo_sgskip.py](https://matplotlib.org/_downloads/cursor_demo_sgskip.py)

View File

@@ -0,0 +1,470 @@
# 自定义投影
通过减轻Matplotlib的许多功能来展示Hammer投影。
![自定义投影示例](https://matplotlib.org/_images/sphx_glr_custom_projection_001.png)
```python
import matplotlib
from matplotlib.axes import Axes
from matplotlib.patches import Circle
from matplotlib.path import Path
from matplotlib.ticker import NullLocator, Formatter, FixedLocator
from matplotlib.transforms import Affine2D, BboxTransformTo, Transform
from matplotlib.projections import register_projection
import matplotlib.spines as mspines
import matplotlib.axis as maxis
import numpy as np
rcParams = matplotlib.rcParams
# This example projection class is rather long, but it is designed to
# illustrate many features, not all of which will be used every time.
# It is also common to factor out a lot of these methods into common
# code used by a number of projections with similar characteristics
# (see geo.py).
class GeoAxes(Axes):
"""
An abstract base class for geographic projections
"""
class ThetaFormatter(Formatter):
"""
Used to format the theta tick labels. Converts the native
unit of radians into degrees and adds a degree symbol.
"""
def __init__(self, round_to=1.0):
self._round_to = round_to
def __call__(self, x, pos=None):
degrees = np.round(np.rad2deg(x) / self._round_to) * self._round_to
if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:
return r"$%0.0f^\circ$" % degrees
else:
return "%0.0f\N{DEGREE SIGN}" % degrees
RESOLUTION = 75
def _init_axis(self):
self.xaxis = maxis.XAxis(self)
self.yaxis = maxis.YAxis(self)
# Do not register xaxis or yaxis with spines -- as done in
# Axes._init_axis() -- until GeoAxes.xaxis.cla() works.
# self.spines['geo'].register_axis(self.yaxis)
self._update_transScale()
def cla(self):
Axes.cla(self)
self.set_longitude_grid(30)
self.set_latitude_grid(15)
self.set_longitude_grid_ends(75)
self.xaxis.set_minor_locator(NullLocator())
self.yaxis.set_minor_locator(NullLocator())
self.xaxis.set_ticks_position('none')
self.yaxis.set_ticks_position('none')
self.yaxis.set_tick_params(label1On=True)
# Why do we need to turn on yaxis tick labels, but
# xaxis tick labels are already on?
self.grid(rcParams['axes.grid'])
Axes.set_xlim(self, -np.pi, np.pi)
Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)
def _set_lim_and_transforms(self):
# A (possibly non-linear) projection on the (already scaled) data
# There are three important coordinate spaces going on here:
#
# 1. Data space: The space of the data itself
#
# 2. Axes space: The unit rectangle (0, 0) to (1, 1)
# covering the entire plot area.
#
# 3. Display space: The coordinates of the resulting image,
# often in pixels or dpi/inch.
# This function makes heavy use of the Transform classes in
# ``lib/matplotlib/transforms.py.`` For more information, see
# the inline documentation there.
# The goal of the first two transformations is to get from the
# data space (in this case longitude and latitude) to axes
# space. It is separated into a non-affine and affine part so
# that the non-affine part does not have to be recomputed when
# a simple affine change to the figure has been made (such as
# resizing the window or changing the dpi).
# 1) The core transformation from data space into
# rectilinear space defined in the HammerTransform class.
self.transProjection = self._get_core_transform(self.RESOLUTION)
# 2) The above has an output range that is not in the unit
# rectangle, so scale and translate it so it fits correctly
# within the axes. The peculiar calculations of xscale and
# yscale are specific to a Aitoff-Hammer projection, so don't
# worry about them too much.
self.transAffine = self._get_affine_transform()
# 3) This is the transformation from axes space to display
# space.
self.transAxes = BboxTransformTo(self.bbox)
# Now put these 3 transforms together -- from data all the way
# to display coordinates. Using the '+' operator, these
# transforms will be applied "in order". The transforms are
# automatically simplified, if possible, by the underlying
# transformation framework.
self.transData = \
self.transProjection + \
self.transAffine + \
self.transAxes
# The main data transformation is set up. Now deal with
# gridlines and tick labels.
# Longitude gridlines and ticklabels. The input to these
# transforms are in display space in x and axes space in y.
# Therefore, the input values will be in range (-xmin, 0),
# (xmax, 1). The goal of these transforms is to go from that
# space to display space. The tick labels will be offset 4
# pixels from the equator.
self._xaxis_pretransform = \
Affine2D() \
.scale(1.0, self._longitude_cap * 2.0) \
.translate(0.0, -self._longitude_cap)
self._xaxis_transform = \
self._xaxis_pretransform + \
self.transData
self._xaxis_text1_transform = \
Affine2D().scale(1.0, 0.0) + \
self.transData + \
Affine2D().translate(0.0, 4.0)
self._xaxis_text2_transform = \
Affine2D().scale(1.0, 0.0) + \
self.transData + \
Affine2D().translate(0.0, -4.0)
# Now set up the transforms for the latitude ticks. The input to
# these transforms are in axes space in x and display space in
# y. Therefore, the input values will be in range (0, -ymin),
# (1, ymax). The goal of these transforms is to go from that
# space to display space. The tick labels will be offset 4
# pixels from the edge of the axes ellipse.
yaxis_stretch = Affine2D().scale(np.pi*2, 1).translate(-np.pi, 0)
yaxis_space = Affine2D().scale(1.0, 1.1)
self._yaxis_transform = \
yaxis_stretch + \
self.transData
yaxis_text_base = \
yaxis_stretch + \
self.transProjection + \
(yaxis_space +
self.transAffine +
self.transAxes)
self._yaxis_text1_transform = \
yaxis_text_base + \
Affine2D().translate(-8.0, 0.0)
self._yaxis_text2_transform = \
yaxis_text_base + \
Affine2D().translate(8.0, 0.0)
def _get_affine_transform(self):
transform = self._get_core_transform(1)
xscale, _ = transform.transform_point((np.pi, 0))
_, yscale = transform.transform_point((0, np.pi / 2.0))
return Affine2D() \
.scale(0.5 / xscale, 0.5 / yscale) \
.translate(0.5, 0.5)
def get_xaxis_transform(self, which='grid'):
"""
Override this method to provide a transformation for the
x-axis tick labels.
Returns a tuple of the form (transform, valign, halign)
"""
if which not in ['tick1', 'tick2', 'grid']:
raise ValueError(
"'which' must be one of 'tick1', 'tick2', or 'grid'")
return self._xaxis_transform
def get_xaxis_text1_transform(self, pad):
return self._xaxis_text1_transform, 'bottom', 'center'
def get_xaxis_text2_transform(self, pad):
"""
Override this method to provide a transformation for the
secondary x-axis tick labels.
Returns a tuple of the form (transform, valign, halign)
"""
return self._xaxis_text2_transform, 'top', 'center'
def get_yaxis_transform(self, which='grid'):
"""
Override this method to provide a transformation for the
y-axis grid and ticks.
"""
if which not in ['tick1', 'tick2', 'grid']:
raise ValueError(
"'which' must be one of 'tick1', 'tick2', or 'grid'")
return self._yaxis_transform
def get_yaxis_text1_transform(self, pad):
"""
Override this method to provide a transformation for the
y-axis tick labels.
Returns a tuple of the form (transform, valign, halign)
"""
return self._yaxis_text1_transform, 'center', 'right'
def get_yaxis_text2_transform(self, pad):
"""
Override this method to provide a transformation for the
secondary y-axis tick labels.
Returns a tuple of the form (transform, valign, halign)
"""
return self._yaxis_text2_transform, 'center', 'left'
def _gen_axes_patch(self):
"""
Override this method to define the shape that is used for the
background of the plot. It should be a subclass of Patch.
In this case, it is a Circle (that may be warped by the axes
transform into an ellipse). Any data and gridlines will be
clipped to this shape.
"""
return Circle((0.5, 0.5), 0.5)
def _gen_axes_spines(self):
return {'geo': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)}
def set_yscale(self, *args, **kwargs):
if args[0] != 'linear':
raise NotImplementedError
# Prevent the user from applying scales to one or both of the
# axes. In this particular case, scaling the axes wouldn't make
# sense, so we don't allow it.
set_xscale = set_yscale
# Prevent the user from changing the axes limits. In our case, we
# want to display the whole sphere all the time, so we override
# set_xlim and set_ylim to ignore any input. This also applies to
# interactive panning and zooming in the GUI interfaces.
def set_xlim(self, *args, **kwargs):
raise TypeError("It is not possible to change axes limits "
"for geographic projections. Please consider "
"using Basemap or Cartopy.")
set_ylim = set_xlim
def format_coord(self, lon, lat):
"""
Override this method to change how the values are displayed in
the status bar.
In this case, we want them to be displayed in degrees N/S/E/W.
"""
lon, lat = np.rad2deg([lon, lat])
if lat >= 0.0:
ns = 'N'
else:
ns = 'S'
if lon >= 0.0:
ew = 'E'
else:
ew = 'W'
return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s'
% (abs(lat), ns, abs(lon), ew))
def set_longitude_grid(self, degrees):
"""
Set the number of degrees between each longitude grid.
This is an example method that is specific to this projection
class -- it provides a more convenient interface to set the
ticking than set_xticks would.
"""
# Skip -180 and 180, which are the fixed limits.
grid = np.arange(-180 + degrees, 180, degrees)
self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))
self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))
def set_latitude_grid(self, degrees):
"""
Set the number of degrees between each longitude grid.
This is an example method that is specific to this projection
class -- it provides a more convenient interface than
set_yticks would.
"""
# Skip -90 and 90, which are the fixed limits.
grid = np.arange(-90 + degrees, 90, degrees)
self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))
self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))
def set_longitude_grid_ends(self, degrees):
"""
Set the latitude(s) at which to stop drawing the longitude grids.
Often, in geographic projections, you wouldn't want to draw
longitude gridlines near the poles. This allows the user to
specify the degree at which to stop drawing longitude grids.
This is an example method that is specific to this projection
class -- it provides an interface to something that has no
analogy in the base Axes class.
"""
self._longitude_cap = np.deg2rad(degrees)
self._xaxis_pretransform \
.clear() \
.scale(1.0, self._longitude_cap * 2.0) \
.translate(0.0, -self._longitude_cap)
def get_data_ratio(self):
"""
Return the aspect ratio of the data itself.
This method should be overridden by any Axes that have a
fixed data ratio.
"""
return 1.0
# Interactive panning and zooming is not supported with this projection,
# so we override all of the following methods to disable it.
def can_zoom(self):
"""
Return *True* if this axes supports the zoom box button functionality.
This axes object does not support interactive zoom box.
"""
return False
def can_pan(self):
"""
Return *True* if this axes supports the pan/zoom button functionality.
This axes object does not support interactive pan/zoom.
"""
return False
def start_pan(self, x, y, button):
pass
def end_pan(self):
pass
def drag_pan(self, button, key, x, y):
pass
class HammerAxes(GeoAxes):
"""
A custom class for the Aitoff-Hammer projection, an equal-area map
projection.
https://en.wikipedia.org/wiki/Hammer_projection
"""
# The projection must specify a name. This will be used by the
# user to select the projection,
# i.e. ``subplot(111, projection='custom_hammer')``.
name = 'custom_hammer'
class HammerTransform(Transform):
"""
The base Hammer transform.
"""
input_dims = 2
output_dims = 2
is_separable = False
def __init__(self, resolution):
"""
Create a new Hammer transform. Resolution is the number of steps
to interpolate between each input line segment to approximate its
path in curved Hammer space.
"""
Transform.__init__(self)
self._resolution = resolution
def transform_non_affine(self, ll):
longitude, latitude = ll.T
# Pre-compute some values
half_long = longitude / 2
cos_latitude = np.cos(latitude)
sqrt2 = np.sqrt(2)
alpha = np.sqrt(1 + cos_latitude * np.cos(half_long))
x = (2 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha
y = (sqrt2 * np.sin(latitude)) / alpha
return np.column_stack([x, y])
transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__
def transform_path_non_affine(self, path):
# vertices = path.vertices
ipath = path.interpolated(self._resolution)
return Path(self.transform(ipath.vertices), ipath.codes)
transform_path_non_affine.__doc__ = \
Transform.transform_path_non_affine.__doc__
def inverted(self):
return HammerAxes.InvertedHammerTransform(self._resolution)
inverted.__doc__ = Transform.inverted.__doc__
class InvertedHammerTransform(Transform):
input_dims = 2
output_dims = 2
is_separable = False
def __init__(self, resolution):
Transform.__init__(self)
self._resolution = resolution
def transform_non_affine(self, xy):
x, y = xy.T
z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2)
longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1)))
latitude = np.arcsin(y*z)
return np.column_stack([longitude, latitude])
transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__
def inverted(self):
return HammerAxes.HammerTransform(self._resolution)
inverted.__doc__ = Transform.inverted.__doc__
def __init__(self, *args, **kwargs):
self._longitude_cap = np.pi / 2.0
GeoAxes.__init__(self, *args, **kwargs)
self.set_aspect(0.5, adjustable='box', anchor='C')
self.cla()
def _get_core_transform(self, resolution):
return self.HammerTransform(resolution)
# Now register the projection with matplotlib so the user can select
# it.
register_projection(HammerAxes)
if __name__ == '__main__':
import matplotlib.pyplot as plt
# Now make a simple example using the custom projection.
plt.subplot(111, projection="custom_hammer")
p = plt.plot([-1, 1, 1], [-1, -1, 1], "o-")
plt.grid(True)
plt.show()
```
## 下载这个示例
- [下载python源码: custom_projection.py](https://matplotlib.org/_downloads/custom_projection.py)
- [下载Jupyter notebook: custom_projection.ipynb](https://matplotlib.org/_downloads/custom_projection.ipynb)

View File

@@ -0,0 +1,57 @@
# 自定义Rc
我不是想在这里做一个好看的人物而只是为了展示一些动态定制rc params的例子
如果您希望以交互方式工作,并且需要为图形创建不同的默认设置(例如,一组用于发布的默认设置,一组用于交互式探索),您可能希望在自定义模块中定义一些设置默认值的函数, 例如,:
```python
def set_pub():
rc('font', weight='bold') # bold fonts are easier to see
rc('tick', labelsize=15) # tick labels bigger
rc('lines', lw=1, color='k') # thicker black lines
rc('grid', c='0.5', ls='-', lw=0.5) # solid gray grid lines
rc('savefig', dpi=300) # higher res outputs
```
然后,当您以交互方式工作时,您只需要:
```python
>>> set_pub()
>>> subplot(111)
>>> plot([1,2,3])
>>> savefig('myfig')
>>> rcdefaults() # restore the defaults
```
![自定义Rc示例](https://matplotlib.org/_images/sphx_glr_customize_rc_001.png)
```python
import matplotlib.pyplot as plt
plt.subplot(311)
plt.plot([1, 2, 3])
# the axes attributes need to be set before the call to subplot
plt.rc('font', weight='bold')
plt.rc('xtick.major', size=5, pad=7)
plt.rc('xtick', labelsize=15)
# using aliases for color, linestyle and linewidth; gray, solid, thick
plt.rc('grid', c='0.5', ls='-', lw=5)
plt.rc('lines', lw=2, color='g')
plt.subplot(312)
plt.plot([1, 2, 3])
plt.grid(True)
plt.rcdefaults()
plt.subplot(313)
plt.plot([1, 2, 3])
plt.grid(True)
plt.show()
```
## 下载这个示例
- [下载python源码: customize_rc.py](https://matplotlib.org/_downloads/customize_rc.py)
- [下载Jupyter notebook: customize_rc.ipynb](https://matplotlib.org/_downloads/customize_rc.ipynb)

View File

@@ -0,0 +1,334 @@
# 演示Agg过滤器
![演示Agg过滤器示例](https://matplotlib.org/_images/sphx_glr_demo_agg_filter_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
import matplotlib.transforms as mtransforms
from matplotlib.colors import LightSource
from matplotlib.artist import Artist
def smooth1d(x, window_len):
# copied from http://www.scipy.org/Cookbook/SignalSmooth
s = np.r_[2*x[0] - x[window_len:1:-1], x, 2*x[-1] - x[-1:-window_len:-1]]
w = np.hanning(window_len)
y = np.convolve(w/w.sum(), s, mode='same')
return y[window_len-1:-window_len+1]
def smooth2d(A, sigma=3):
window_len = max(int(sigma), 3)*2 + 1
A1 = np.array([smooth1d(x, window_len) for x in np.asarray(A)])
A2 = np.transpose(A1)
A3 = np.array([smooth1d(x, window_len) for x in A2])
A4 = np.transpose(A3)
return A4
class BaseFilter(object):
def prepare_image(self, src_image, dpi, pad):
ny, nx, depth = src_image.shape
# tgt_image = np.zeros([pad*2+ny, pad*2+nx, depth], dtype="d")
padded_src = np.zeros([pad*2 + ny, pad*2 + nx, depth], dtype="d")
padded_src[pad:-pad, pad:-pad, :] = src_image[:, :, :]
return padded_src # , tgt_image
def get_pad(self, dpi):
return 0
def __call__(self, im, dpi):
pad = self.get_pad(dpi)
padded_src = self.prepare_image(im, dpi, pad)
tgt_image = self.process_image(padded_src, dpi)
return tgt_image, -pad, -pad
class OffsetFilter(BaseFilter):
def __init__(self, offsets=None):
if offsets is None:
self.offsets = (0, 0)
else:
self.offsets = offsets
def get_pad(self, dpi):
return int(max(*self.offsets)/72.*dpi)
def process_image(self, padded_src, dpi):
ox, oy = self.offsets
a1 = np.roll(padded_src, int(ox/72.*dpi), axis=1)
a2 = np.roll(a1, -int(oy/72.*dpi), axis=0)
return a2
class GaussianFilter(BaseFilter):
"simple gauss filter"
def __init__(self, sigma, alpha=0.5, color=None):
self.sigma = sigma
self.alpha = alpha
if color is None:
self.color = (0, 0, 0)
else:
self.color = color
def get_pad(self, dpi):
return int(self.sigma*3/72.*dpi)
def process_image(self, padded_src, dpi):
# offsetx, offsety = int(self.offsets[0]), int(self.offsets[1])
tgt_image = np.zeros_like(padded_src)
aa = smooth2d(padded_src[:, :, -1]*self.alpha,
self.sigma/72.*dpi)
tgt_image[:, :, -1] = aa
tgt_image[:, :, :-1] = self.color
return tgt_image
class DropShadowFilter(BaseFilter):
def __init__(self, sigma, alpha=0.3, color=None, offsets=None):
self.gauss_filter = GaussianFilter(sigma, alpha, color)
self.offset_filter = OffsetFilter(offsets)
def get_pad(self, dpi):
return max(self.gauss_filter.get_pad(dpi),
self.offset_filter.get_pad(dpi))
def process_image(self, padded_src, dpi):
t1 = self.gauss_filter.process_image(padded_src, dpi)
t2 = self.offset_filter.process_image(t1, dpi)
return t2
class LightFilter(BaseFilter):
"simple gauss filter"
def __init__(self, sigma, fraction=0.5):
self.gauss_filter = GaussianFilter(sigma, alpha=1)
self.light_source = LightSource()
self.fraction = fraction
def get_pad(self, dpi):
return self.gauss_filter.get_pad(dpi)
def process_image(self, padded_src, dpi):
t1 = self.gauss_filter.process_image(padded_src, dpi)
elevation = t1[:, :, 3]
rgb = padded_src[:, :, :3]
rgb2 = self.light_source.shade_rgb(rgb, elevation,
fraction=self.fraction)
tgt = np.empty_like(padded_src)
tgt[:, :, :3] = rgb2
tgt[:, :, 3] = padded_src[:, :, 3]
return tgt
class GrowFilter(BaseFilter):
"enlarge the area"
def __init__(self, pixels, color=None):
self.pixels = pixels
if color is None:
self.color = (1, 1, 1)
else:
self.color = color
def __call__(self, im, dpi):
pad = self.pixels
ny, nx, depth = im.shape
new_im = np.empty([pad*2 + ny, pad*2 + nx, depth], dtype="d")
alpha = new_im[:, :, 3]
alpha.fill(0)
alpha[pad:-pad, pad:-pad] = im[:, :, -1]
alpha2 = np.clip(smooth2d(alpha, self.pixels/72.*dpi) * 5, 0, 1)
new_im[:, :, -1] = alpha2
new_im[:, :, :-1] = self.color
offsetx, offsety = -pad, -pad
return new_im, offsetx, offsety
class FilteredArtistList(Artist):
"""
A simple container to draw filtered artist.
"""
def __init__(self, artist_list, filter):
self._artist_list = artist_list
self._filter = filter
Artist.__init__(self)
def draw(self, renderer):
renderer.start_rasterizing()
renderer.start_filter()
for a in self._artist_list:
a.draw(renderer)
renderer.stop_filter(self._filter)
renderer.stop_rasterizing()
def filtered_text(ax):
# mostly copied from contour_demo.py
# prepare image
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
# draw
im = ax.imshow(Z, interpolation='bilinear', origin='lower',
cmap=cm.gray, extent=(-3, 3, -2, 2))
levels = np.arange(-1.2, 1.6, 0.2)
CS = ax.contour(Z, levels,
origin='lower',
linewidths=2,
extent=(-3, 3, -2, 2))
ax.set_aspect("auto")
# contour label
cl = ax.clabel(CS, levels[1::2], # label every second level
inline=1,
fmt='%1.1f',
fontsize=11)
# change clable color to black
from matplotlib.patheffects import Normal
for t in cl:
t.set_color("k")
# to force TextPath (i.e., same font in all backends)
t.set_path_effects([Normal()])
# Add white glows to improve visibility of labels.
white_glows = FilteredArtistList(cl, GrowFilter(3))
ax.add_artist(white_glows)
white_glows.set_zorder(cl[0].get_zorder() - 0.1)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def drop_shadow_line(ax):
# copied from examples/misc/svg_filter_line.py
# draw lines
l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-",
mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
gauss = DropShadowFilter(4)
for l in [l1, l2]:
# draw shadows with same lines with slight offset.
xx = l.get_xdata()
yy = l.get_ydata()
shadow, = ax.plot(xx, yy)
shadow.update_from(l)
# offset transform
ot = mtransforms.offset_copy(l.get_transform(), ax.figure,
x=4.0, y=-6.0, units='points')
shadow.set_transform(ot)
# adjust zorder of the shadow lines so that it is drawn below the
# original lines
shadow.set_zorder(l.get_zorder() - 0.5)
shadow.set_agg_filter(gauss)
shadow.set_rasterized(True) # to support mixed-mode renderers
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def drop_shadow_patches(ax):
# Copied from barchart_demo.py
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
rects1 = ax.bar(ind, menMeans, width, color='r', ec="w", lw=2)
womenMeans = (25, 32, 34, 20, 25)
rects2 = ax.bar(ind + width + 0.1, womenMeans, width,
color='y', ec="w", lw=2)
# gauss = GaussianFilter(1.5, offsets=(1,1), )
gauss = DropShadowFilter(5, offsets=(1, 1), )
shadow = FilteredArtistList(rects1 + rects2, gauss)
ax.add_artist(shadow)
shadow.set_zorder(rects1[0].get_zorder() - 0.1)
ax.set_ylim(0, 40)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def light_filter_pie(ax):
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
pies = ax.pie(fracs, explode=explode)
ax.patch.set_visible(True)
light_filter = LightFilter(9)
for p in pies[0]:
p.set_agg_filter(light_filter)
p.set_rasterized(True) # to support mixed-mode renderers
p.set(ec="none",
lw=2)
gauss = DropShadowFilter(9, offsets=(3, 4), alpha=0.7)
shadow = FilteredArtistList(pies[0], gauss)
ax.add_artist(shadow)
shadow.set_zorder(pies[0][0].get_zorder() - 0.1)
if 1:
plt.figure(1, figsize=(6, 6))
plt.subplots_adjust(left=0.05, right=0.95)
ax = plt.subplot(221)
filtered_text(ax)
ax = plt.subplot(222)
drop_shadow_line(ax)
ax = plt.subplot(223)
drop_shadow_patches(ax)
ax = plt.subplot(224)
ax.set_aspect(1)
light_filter_pie(ax)
ax.set_frame_on(True)
plt.show()
```
## 下载这个示例
- [下载python源码: demo_agg_filter.py](https://matplotlib.org/_downloads/demo_agg_filter.py)
- [下载Jupyter notebook: demo_agg_filter.ipynb](https://matplotlib.org/_downloads/demo_agg_filter.ipynb)

View File

@@ -0,0 +1,105 @@
# 演示丝带盒
![演示丝带盒示例](https://matplotlib.org/_images/sphx_glr_demo_ribbon_box_001.png)
```python
import numpy as np
from matplotlib import cbook, colors as mcolors
from matplotlib.image import BboxImage
import matplotlib.pyplot as plt
class RibbonBox:
original_image = plt.imread(
cbook.get_sample_data("Minduka_Present_Blue_Pack.png"))
cut_location = 70
b_and_h = original_image[:, :, 2:3]
color = original_image[:, :, 2:3] - original_image[:, :, 0:1]
alpha = original_image[:, :, 3:4]
nx = original_image.shape[1]
def __init__(self, color):
rgb = mcolors.to_rgba(color)[:3]
self.im = np.dstack(
[self.b_and_h - self.color * (1 - np.array(rgb)), self.alpha])
def get_stretched_image(self, stretch_factor):
stretch_factor = max(stretch_factor, 1)
ny, nx, nch = self.im.shape
ny2 = int(ny*stretch_factor)
return np.vstack(
[self.im[:self.cut_location],
np.broadcast_to(
self.im[self.cut_location], (ny2 - ny, nx, nch)),
self.im[self.cut_location:]])
class RibbonBoxImage(BboxImage):
zorder = 1
def __init__(self, bbox, color, **kwargs):
super().__init__(bbox, **kwargs)
self._ribbonbox = RibbonBox(color)
def draw(self, renderer, *args, **kwargs):
bbox = self.get_window_extent(renderer)
stretch_factor = bbox.height / bbox.width
ny = int(stretch_factor*self._ribbonbox.nx)
if self.get_array() is None or self.get_array().shape[0] != ny:
arr = self._ribbonbox.get_stretched_image(stretch_factor)
self.set_array(arr)
super().draw(renderer, *args, **kwargs)
if True:
from matplotlib.transforms import Bbox, TransformedBbox
from matplotlib.ticker import ScalarFormatter
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
years = np.arange(2004, 2009)
box_colors = [(0.8, 0.2, 0.2),
(0.2, 0.8, 0.2),
(0.2, 0.2, 0.8),
(0.7, 0.5, 0.8),
(0.3, 0.8, 0.7),
]
heights = np.random.random(years.shape) * 7000 + 3000
fmt = ScalarFormatter(useOffset=False)
ax.xaxis.set_major_formatter(fmt)
for year, h, bc in zip(years, heights, box_colors):
bbox0 = Bbox.from_extents(year - 0.4, 0., year + 0.4, h)
bbox = TransformedBbox(bbox0, ax.transData)
rb_patch = RibbonBoxImage(bbox, bc, interpolation="bicubic")
ax.add_artist(rb_patch)
ax.annotate(r"%d" % (int(h/100.)*100),
(year, h), va="bottom", ha="center")
patch_gradient = BboxImage(ax.bbox, interpolation="bicubic", zorder=0.1)
gradient = np.zeros((2, 2, 4))
gradient[:, :, :3] = [1, 1, 0.]
gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]] # alpha channel
patch_gradient.set_array(gradient)
ax.add_artist(patch_gradient)
ax.set_xlim(years[0] - 0.5, years[-1] + 0.5)
ax.set_ylim(0, 10000)
plt.show()
```
## 下载这个示例
- [下载python源码: demo_ribbon_box.py](https://matplotlib.org/_downloads/demo_ribbon_box.py)
- [下载Jupyter notebook: demo_ribbon_box.ipynb](https://matplotlib.org/_downloads/demo_ribbon_box.ipynb)

View File

@@ -0,0 +1,34 @@
# 填充螺旋
![填充螺旋示例](https://matplotlib.org/_images/sphx_glr_fill_spiral_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
theta = np.arange(0, 8*np.pi, 0.1)
a = 1
b = .2
for dt in np.arange(0, 2*np.pi, np.pi/2.0):
x = a*np.cos(theta + dt)*np.exp(b*theta)
y = a*np.sin(theta + dt)*np.exp(b*theta)
dt = dt + np.pi/4.0
x2 = a*np.cos(theta + dt)*np.exp(b*theta)
y2 = a*np.sin(theta + dt)*np.exp(b*theta)
xf = np.concatenate((x, x2[::-1]))
yf = np.concatenate((y, y2[::-1]))
p1 = plt.fill(xf, yf)
plt.show()
```
## 下载这个示例
- [下载python源码: fill_spiral.py](https://matplotlib.org/_downloads/fill_spiral.py)
- [下载Jupyter notebook: fill_spiral.ipynb](https://matplotlib.org/_downloads/fill_spiral.ipynb)

View File

@@ -0,0 +1,47 @@
# Findobj演示
递归查找符合某些条件的所有对象
![Findobj演示](https://matplotlib.org/_images/sphx_glr_findobj_demo_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.text as text
a = np.arange(0, 3, .02)
b = np.arange(0, 3, .02)
c = np.exp(a)
d = c[::-1]
fig, ax = plt.subplots()
plt.plot(a, c, 'k--', a, d, 'k:', a, c + d, 'k')
plt.legend(('Model length', 'Data length', 'Total message length'),
loc='upper center', shadow=True)
plt.ylim([-1, 20])
plt.grid(False)
plt.xlabel('Model complexity --->')
plt.ylabel('Message length --->')
plt.title('Minimum Message Length')
# match on arbitrary function
def myfunc(x):
return hasattr(x, 'set_color') and not hasattr(x, 'set_facecolor')
for o in fig.findobj(myfunc):
o.set_color('blue')
# match on class instances
for o in fig.findobj(text.Text):
o.set_fontstyle('italic')
plt.show()
```
## 下载这个示例
- [下载python源码: findobj_demo.py](https://matplotlib.org/_downloads/findobj_demo.py)
- [下载Jupyter notebook: findobj_demo.ipynb](https://matplotlib.org/_downloads/findobj_demo.ipynb)

View File

@@ -0,0 +1,55 @@
# 字体索引
一个小示例它展示了对字体表的各种索引是如何相互关联的。主要是为MPL开发商.。
输出:
```python
(6, 0, 519, 576)
36 57 65 86
AV 0
AV 0
AV 0
AV 0
```
```python
import matplotlib
from matplotlib.ft2font import FT2Font, KERNING_DEFAULT, KERNING_UNFITTED, KERNING_UNSCALED
fname = matplotlib.get_data_path() + '/fonts/ttf/DejaVuSans.ttf'
font = FT2Font(fname)
font.set_charmap(0)
codes = font.get_charmap().items()
#dsu = [(ccode, glyphind) for ccode, glyphind in codes]
#dsu.sort()
#for ccode, glyphind in dsu:
# try: name = font.get_glyph_name(glyphind)
# except RuntimeError: pass
# else: print('% 4d % 4d %s %s' % (glyphind, ccode, hex(int(ccode)), name))
# make a charname to charcode and glyphind dictionary
coded = {}
glyphd = {}
for ccode, glyphind in codes:
name = font.get_glyph_name(glyphind)
coded[name] = ccode
glyphd[name] = glyphind
code = coded['A']
glyph = font.load_char(code)
print(glyph.bbox)
print(glyphd['A'], glyphd['V'], coded['A'], coded['V'])
print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_DEFAULT))
print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_UNFITTED))
print('AV', font.get_kerning(glyphd['A'], glyphd['V'], KERNING_UNSCALED))
print('AV', font.get_kerning(glyphd['A'], glyphd['T'], KERNING_UNSCALED))
```
## 下载这个示例
- [下载python源码: font_indexing.py](https://matplotlib.org/_downloads/font_indexing.py)
- [下载Jupyter notebook: font_indexing.ipynb](https://matplotlib.org/_downloads/font_indexing.ipynb)

View File

@@ -0,0 +1,103 @@
# Ftface属性
这是一个演示脚本向您展示如何使用FT2Font对象的所有属性。这些描述了全局字体属性。对于单个字符度量标准请使用load_char返回的Glyph对象
输出:
```python
Num faces : 1
Num glyphs : 5343
Family name : DejaVu Sans
Style name : Oblique
PS name : DejaVuSans-Oblique
Num fixed : 0
Bbox : (-2080, -717, 3398, 2187)
EM : 2048
Ascender : 1901
Descender : -483
Height : 2384
Max adv width : 3461
Max adv height : 2384
Underline pos : -175
Underline thickness : 90
Italic : True
Bold : False
Scalable : True
Fixed sizes : False
Fixed width : False
SFNT : False
Horizontal : False
Vertical : False
Kerning : False
Fast glyphs : False
Multiple masters : False
Glyph names : False
External stream : False
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'ascender', 'bbox', 'clear', 'descender', 'draw_glyph_to_bitmap', 'draw_glyphs_to_bitmap', 'face_flags', 'family_name', 'fname', 'get_bitmap_offset', 'get_char_index', 'get_charmap', 'get_descent', 'get_glyph_name', 'get_image', 'get_kerning', 'get_name_index', 'get_num_glyphs', 'get_path', 'get_ps_font_info', 'get_sfnt', 'get_sfnt_table', 'get_width_height', 'get_xys', 'height', 'load_char', 'load_glyph', 'max_advance_height', 'max_advance_width', 'num_charmaps', 'num_faces', 'num_fixed_sizes', 'num_glyphs', 'postscript_name', 'scalable', 'select_charmap', 'set_charmap', 'set_size', 'set_text', 'style_flags', 'style_name', 'underline_position', 'underline_thickness', 'units_per_EM']
<built-in method get_kerning of matplotlib.ft2font.FT2Font object at 0x7f6451677ed0>
```
```python
import matplotlib
import matplotlib.ft2font as ft
#fname = '/usr/local/share/matplotlib/VeraIt.ttf'
fname = matplotlib.get_data_path() + '/fonts/ttf/DejaVuSans-Oblique.ttf'
#fname = '/usr/local/share/matplotlib/cmr10.ttf'
font = ft.FT2Font(fname)
print('Num faces :', font.num_faces) # number of faces in file
print('Num glyphs :', font.num_glyphs) # number of glyphs in the face
print('Family name :', font.family_name) # face family name
print('Style name :', font.style_name) # face style name
print('PS name :', font.postscript_name) # the postscript name
print('Num fixed :', font.num_fixed_sizes) # number of embedded bitmap in face
# the following are only available if face.scalable
if font.scalable:
# the face global bounding box (xmin, ymin, xmax, ymax)
print('Bbox :', font.bbox)
# number of font units covered by the EM
print('EM :', font.units_per_EM)
# the ascender in 26.6 units
print('Ascender :', font.ascender)
# the descender in 26.6 units
print('Descender :', font.descender)
# the height in 26.6 units
print('Height :', font.height)
# maximum horizontal cursor advance
print('Max adv width :', font.max_advance_width)
# same for vertical layout
print('Max adv height :', font.max_advance_height)
# vertical position of the underline bar
print('Underline pos :', font.underline_position)
# vertical thickness of the underline
print('Underline thickness :', font.underline_thickness)
for style in ('Italic',
'Bold',
'Scalable',
'Fixed sizes',
'Fixed width',
'SFNT',
'Horizontal',
'Vertical',
'Kerning',
'Fast glyphs',
'Multiple masters',
'Glyph names',
'External stream'):
bitpos = getattr(ft, style.replace(' ', '_').upper()) - 1
print('%-17s:' % style, bool(font.style_flags & (1 << bitpos)))
print(dir(font))
print(font.get_kerning)
```
## 下载这个示例
- [下载python源码: ftface_props.py](https://matplotlib.org/_downloads/ftface_props.py)
- [下载Jupyter notebook: ftface_props.ipynb](https://matplotlib.org/_downloads/ftface_props.ipynb)

View File

@@ -0,0 +1,92 @@
# 使用“矩形”和“多边形”构建直方图
使用路径补丁绘制矩形。 使用大量Rectangle实例的技术或使用PolyCollections的更快方法是在我们在mpl中使用moveto / linetoclosepoly等的正确路径之前实现的。 现在我们拥有它们我们可以使用PathCollection更有效地绘制具有同质属性的常规形状对象的集合。 这个例子创建了一个直方图 - 在开始时设置顶点数组的工作量更大,但对于大量对象来说它应该更快。
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
fig, ax = plt.subplots()
# Fixing random state for reproducibility
np.random.seed(19680801)
# histogram our data with numpy
data = np.random.randn(1000)
n, bins = np.histogram(data, 50)
# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
# we need a (numrects x numsides x 2) numpy array for the path helper
# function to build a compound path
XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T
# get the Path object
barpath = path.Path.make_compound_path_from_polys(XY)
# make a patch out of it
patch = patches.PathPatch(barpath)
ax.add_patch(patch)
# update the view limits
ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())
plt.show()
```
![使用“矩形”和“多边形”构建直方图示例](https://matplotlib.org/_images/sphx_glr_histogram_path_001.png)
应该注意的是,我们可以使用顶点和代码直接创建复合路径,而不是创建三维数组并使用[make_compound_path_from_polys](https://matplotlib.org/api/path_api.html#matplotlib.path.Path.make_compound_path_from_polys),如下所示
```python
nrects = len(left)
nverts = nrects*(1+3+1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
barpath = path.Path(verts, codes)
```
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.patches
matplotlib.patches.PathPatch
matplotlib.path
matplotlib.path.Path
matplotlib.path.Path.make_compound_path_from_polys
matplotlib.axes.Axes.add_patch
matplotlib.collections.PathCollection
# This example shows an alternative to
matplotlib.collections.PolyCollection
matplotlib.axes.Axes.hist
```
## 下载这个示例
- [下载python源码: histogram_path.py](https://matplotlib.org/_downloads/histogram_path.py)
- [下载Jupyter notebook: histogram_path.ipynb](https://matplotlib.org/_downloads/histogram_path.ipynb)

View File

@@ -0,0 +1,39 @@
# 超链接
此示例演示如何在各种元素上设置超链接。
这目前只适用于SVG后端。
```python
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
```
```python
f = plt.figure()
s = plt.scatter([1, 2, 3], [4, 5, 6])
s.set_urls(['http://www.bbc.co.uk/news', 'http://www.google.com', None])
f.savefig('scatter.svg')
```
```python
f = plt.figure()
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray,
origin='lower', extent=[-3, 3, -3, 3])
im.set_url('http://www.google.com')
f.savefig('image.svg')
```
## 下载这个示例
- [下载python源码: hyperlinks_sgskip.py](https://matplotlib.org/_downloads/hyperlinks_sgskip.py)
- [下载Jupyter notebook: hyperlinks_sgskip.ipynb](https://matplotlib.org/_downloads/hyperlinks_sgskip.ipynb)

View File

@@ -0,0 +1,35 @@
# 图像缩略图
您可以使用matplotlib从现有图像生成缩略图。matplotlib本身支持输入端的PNG文件如果安装了PIL则透明地支持其他图像类型。
```python
# build thumbnails of all images in a directory
import sys
import os
import glob
import matplotlib.image as image
if len(sys.argv) != 2:
print('Usage: python %s IMAGEDIR' % __file__)
raise SystemExit
indir = sys.argv[1]
if not os.path.isdir(indir):
print('Could not find input directory "%s"' % indir)
raise SystemExit
outdir = 'thumbs'
if not os.path.exists(outdir):
os.makedirs(outdir)
for fname in glob.glob(os.path.join(indir, '*.png')):
basedir, basename = os.path.split(fname)
outfile = os.path.join(outdir, basename)
fig = image.thumbnail(fname, outfile, scale=0.15)
print('saved thumbnail of %s to %s' % (fname, outfile))
```
## 下载这个示例
- [下载python源码: image_thumbnail_sgskip.py](https://matplotlib.org/_downloads/image_thumbnail_sgskip.py)
- [下载Jupyter notebook: image_thumbnail_sgskip.ipynb](https://matplotlib.org/_downloads/image_thumbnail_sgskip.ipynb)

View File

@@ -0,0 +1,29 @@
# 用关键字绘图
在某些情况下,您可以使用允许您使用字符串访问特定变量的格式的数据。 例如,使用 [numpy.recarray](https://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.html#numpy.recarray) 或[pandas.DataFrame](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html#pandas.DataFrame)。
Matplotlib允许您使用data关键字参数提供此类对象。如果提供则可以生成具有与这些变量对应的字符串的图。
![用关键字绘图示例](https://matplotlib.org/_images/sphx_glr_keyword_plotting_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
fig, ax = plt.subplots()
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set(xlabel='entry a', ylabel='entry b')
plt.show()
```
## 下载这个示例
- [下载python源码: keyword_plotting.py](https://matplotlib.org/_downloads/keyword_plotting.py)
- [下载Jupyter notebook: keyword_plotting.ipynb](https://matplotlib.org/_downloads/keyword_plotting.ipynb)

View File

@@ -0,0 +1,33 @@
# 负载转换器
![负载转换器示例](https://matplotlib.org/_images/sphx_glr_load_converter_001.png)
输出:
```python
loading /home/tcaswell/mc3/envs/dd37/lib/python3.7/site-packages/matplotlib/mpl-data/sample_data/msft.csv
```
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.dates import bytespdate2num
datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
print('loading', datafile)
dates, closes = np.loadtxt(datafile, delimiter=',',
converters={0: bytespdate2num('%d-%b-%y')},
skiprows=1, usecols=(0, 2), unpack=True)
fig, ax = plt.subplots()
ax.plot_date(dates, closes, '-')
fig.autofmt_xdate()
plt.show()
```
## 下载这个示例
- [下载python源码: load_converter.py](https://matplotlib.org/_downloads/load_converter.py)
- [下载Jupyter notebook: load_converter.ipynb](https://matplotlib.org/_downloads/load_converter.ipynb)

View File

@@ -0,0 +1,92 @@
# Matplotlib标志
显示一些matplotlib徽标。
感谢Tony Yu <tsyu80@gmail.com>的标志设计
![Matplotlib标志示例](https://matplotlib.org/_images/sphx_glr_logos2_001.png)
```python
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
mpl.rcParams['xtick.labelsize'] = 10
mpl.rcParams['ytick.labelsize'] = 12
mpl.rcParams['axes.edgecolor'] = 'gray'
axalpha = 0.05
figcolor = 'white'
dpi = 80
fig = plt.figure(figsize=(6, 1.1), dpi=dpi)
fig.patch.set_edgecolor(figcolor)
fig.patch.set_facecolor(figcolor)
def add_math_background():
ax = fig.add_axes([0., 0., 1., 1.])
text = []
text.append(
(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 "
r"\left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - "
r"\alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} "
r"}{U^{0\beta}_{\rho_1 \sigma_2}}\right]$", (0.7, 0.2), 20))
text.append((r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} "
r"= -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$",
(0.35, 0.9), 20))
text.append((r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$",
(0.15, 0.3), 25))
text.append((r"$F_G = G\frac{m_1m_2}{r^2}$",
(0.85, 0.7), 30))
for eq, (x, y), size in text:
ax.text(x, y, eq, ha='center', va='center', color="#11557c",
alpha=0.25, transform=ax.transAxes, fontsize=size)
ax.set_axis_off()
return ax
def add_matplotlib_text(ax):
ax.text(0.95, 0.5, 'matplotlib', color='#11557c', fontsize=65,
ha='right', va='center', alpha=1.0, transform=ax.transAxes)
def add_polar_bar():
ax = fig.add_axes([0.025, 0.075, 0.2, 0.85], projection='polar')
ax.patch.set_alpha(axalpha)
ax.set_axisbelow(True)
N = 7
arc = 2. * np.pi
theta = np.arange(0.0, arc, arc/N)
radii = 10 * np.array([0.2, 0.6, 0.8, 0.7, 0.4, 0.5, 0.8])
width = np.pi / 4 * np.array([0.4, 0.4, 0.6, 0.8, 0.2, 0.5, 0.3])
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r, bar in zip(radii, bars):
bar.set_facecolor(cm.jet(r/10.))
bar.set_alpha(0.6)
ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
ax.grid(lw=0.8, alpha=0.9, ls='-', color='0.5')
ax.set_yticks(np.arange(1, 9, 2))
ax.set_rmax(9)
if __name__ == '__main__':
main_axes = add_math_background()
add_polar_bar()
add_matplotlib_text(main_axes)
plt.show()
```
## 下载这个示例
- [下载python源码: logos2.py](https://matplotlib.org/_downloads/logos2.py)
- [下载Jupyter notebook: logos2.ipynb](https://matplotlib.org/_downloads/logos2.ipynb)

View File

@@ -0,0 +1,54 @@
# 多页PDF
这是一个创建包含多个页面的pdf文件以及向pdf文件添加元数据和注释的演示。
如果要使用LaTeX使用多页pdf文件则需要使用 ``matplotlib.backends.backend_pgf`` 导入PdfPages。 但是这个版本不支持 ``attach_note``。
```python
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig() # saves the current figure into a pdf page
plt.close()
# if LaTeX is not installed or error caught, change to `usetex=False`
plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.attach_note("plot of sin(x)") # you can add a pdf note to
# attach metadata to a page
pdf.savefig()
plt.close()
plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x ** 2, 'ko')
plt.title('Page Three')
pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig
plt.close()
# We can also set the file's metadata via the PdfPages object:
d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = 'Jouni K. Sepp\xe4nen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()
```
## 下载这个示例
- [下载python源码: multipage_pdf.py](https://matplotlib.org/_downloads/multipage_pdf.py)
- [下载Jupyter notebook: multipage_pdf.ipynb](https://matplotlib.org/_downloads/multipage_pdf.ipynb)

View File

@@ -0,0 +1,98 @@
# 多进程
演示使用多处理在一个过程中生成数据并在另一个过程中绘图。
由Robert Cimrman撰写
```python
import multiprocessing as mp
import time
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
```
## 进程类
此类绘制从管道接收的数据。
```python
class ProcessPlotter(object):
def __init__(self):
self.x = []
self.y = []
def terminate(self):
plt.close('all')
def call_back(self):
while self.pipe.poll():
command = self.pipe.recv()
if command is None:
self.terminate()
return False
else:
self.x.append(command[0])
self.y.append(command[1])
self.ax.plot(self.x, self.y, 'ro')
self.fig.canvas.draw()
return True
def __call__(self, pipe):
print('starting plotter...')
self.pipe = pipe
self.fig, self.ax = plt.subplots()
timer = self.fig.canvas.new_timer(interval=1000)
timer.add_callback(self.call_back)
timer.start()
print('...done')
plt.show()
```
## 绘图类
此类使用多处理来生成一个进程,以运行上面的类中的代码。 初始化时它会创建一个管道和一个ProcessPlotter实例它将在一个单独的进程中运行。
从命令行运行时父进程将数据发送到生成的进程然后通过ProcessPlotter中指定的回调函数绘制__call__。
```python
class NBPlot(object):
def __init__(self):
self.plot_pipe, plotter_pipe = mp.Pipe()
self.plotter = ProcessPlotter()
self.plot_process = mp.Process(
target=self.plotter, args=(plotter_pipe,), daemon=True)
self.plot_process.start()
def plot(self, finished=False):
send = self.plot_pipe.send
if finished:
send(None)
else:
data = np.random.random(2)
send(data)
def main():
pl = NBPlot()
for ii in range(10):
pl.plot()
time.sleep(0.5)
pl.plot(finished=True)
if __name__ == '__main__':
if plt.get_backend() == "MacOSX":
mp.set_start_method("forkserver")
main()
```
## 下载这个示例
- [下载python源码: multiprocess_sgskip.py](https://matplotlib.org/_downloads/multiprocess_sgskip.py)
- [下载Jupyter notebook: multiprocess_sgskip.ipynb](https://matplotlib.org/_downloads/multiprocess_sgskip.ipynb)

View File

@@ -0,0 +1,52 @@
# 修补效果演示
![修补效果演示](https://matplotlib.org/_images/sphx_glr_patheffect_demo_001.png)
```python
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import numpy as np
if 1:
plt.figure(1, figsize=(8, 3))
ax1 = plt.subplot(131)
ax1.imshow([[1, 2], [2, 3]])
txt = ax1.annotate("test", (1., 1.), (0., 0),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3", lw=2),
size=20, ha="center",
path_effects=[PathEffects.withStroke(linewidth=3,
foreground="w")])
txt.arrow_patch.set_path_effects([
PathEffects.Stroke(linewidth=5, foreground="w"),
PathEffects.Normal()])
pe = [PathEffects.withStroke(linewidth=3,
foreground="w")]
ax1.grid(True, linestyle="-", path_effects=pe)
ax2 = plt.subplot(132)
arr = np.arange(25).reshape((5, 5))
ax2.imshow(arr)
cntr = ax2.contour(arr, colors="k")
plt.setp(cntr.collections, path_effects=[
PathEffects.withStroke(linewidth=3, foreground="w")])
clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
plt.setp(clbls, path_effects=[
PathEffects.withStroke(linewidth=3, foreground="w")])
# shadow as a path effect
ax3 = plt.subplot(133)
p1, = ax3.plot([0, 1], [0, 1])
leg = ax3.legend([p1], ["Line 1"], fancybox=True, loc='upper left')
leg.legendPatch.set_path_effects([PathEffects.withSimplePatchShadow()])
plt.show()
```
## 下载这个示例
- [下载python源码: patheffect_demo.py](https://matplotlib.org/_downloads/patheffect_demo.py)
- [下载Jupyter notebook: patheffect_demo.ipynb](https://matplotlib.org/_downloads/patheffect_demo.ipynb)

View File

@@ -0,0 +1,48 @@
# Plotfile演示
使用plotfile直接从文件绘制数据的示例。
```python
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
fname = cbook.get_sample_data('msft.csv', asfileobj=False)
fname2 = cbook.get_sample_data('data_x_x2_x3.csv', asfileobj=False)
# test 1; use ints
plt.plotfile(fname, (0, 5, 6))
# test 2; use names
plt.plotfile(fname, ('date', 'volume', 'adj_close'))
# test 3; use semilogy for volume
plt.plotfile(fname, ('date', 'volume', 'adj_close'),
plotfuncs={'volume': 'semilogy'})
# test 4; use semilogy for volume
plt.plotfile(fname, (0, 5, 6), plotfuncs={5: 'semilogy'})
# test 5; single subplot
plt.plotfile(fname, ('date', 'open', 'high', 'low', 'close'), subplots=False)
# test 6; labeling, if no names in csv-file
plt.plotfile(fname2, cols=(0, 1, 2), delimiter=' ',
names=['$x$', '$f(x)=x^2$', '$f(x)=x^3$'])
# test 7; more than one file per figure--illustrated here with a single file
plt.plotfile(fname2, cols=(0, 1), delimiter=' ')
plt.plotfile(fname2, cols=(0, 2), newfig=False,
delimiter=' ') # use current figure
plt.xlabel(r'$x$')
plt.ylabel(r'$f(x) = x^2, x^3$')
# test 8; use bar for volume
plt.plotfile(fname, (0, 5, 6), plotfuncs={5: 'bar'})
plt.show()
```
## 下载这个示例
- [下载python源码: plotfile_demo.py](https://matplotlib.org/_downloads/plotfile_demo.py)
- [下载Jupyter notebook: plotfile_demo.ipynb](https://matplotlib.org/_downloads/plotfile_demo.ipynb)

View File

@@ -0,0 +1,20 @@
# 打印标准输出
将PNG打印到标准输出。
用法python print_stdout.py > somefile.png
```python
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.savefig(sys.stdout.buffer)
```
## 下载这个示例
- [下载python源码: print_stdout_sgskip.py](https://matplotlib.org/_downloads/print_stdout_sgskip.py)
- [下载Jupyter notebook: print_stdout_sgskip.ipynb](https://matplotlib.org/_downloads/print_stdout_sgskip.ipynb)

View File

@@ -0,0 +1,72 @@
# Pythonic Matplotlib
有些人喜欢编写更多的面向对象的Python代码而不是使用pyPLOT接口来编写matplotlib。此示例向您展示了如何实现。
除非您是应用程序开发人员否则我建议使用部分pyplot接口尤其是图形closesubplotaxes和show命令。 这些隐藏了您在正常图形创建中不需要看到的很多复杂性例如实例化DPI实例管理图形元素的边界框创建和实现GUI窗口以及在其中嵌入图形。
如果您是应用程序开发人员并希望在应用程序中嵌入matplotlib请遵循示例/ embedding_in_wx.pyexamples / embedding_in_gtk.py或examples / embedding_in_tk.py的主题。 在这种情况下,您需要控制所有图形的创建,将它们嵌入应用程序窗口等。
如果您是Web应用程序开发人员您可能希望使用webapp_demo.py中的示例该示例显示如何直接使用后端agg图形画布而不包含pyplot中存在的全局变量当前图形当前轴 接口。 但请注意没有理由说pyplot接口不适用于Web应用程序开发人员。
如果您在pyplot接口中编写的示例目录中看到一个示例并且您希望使用真正的python方法调用来模拟它则可以轻松进行映射。 其中许多示例使用“set”来控制图形属性。 以下是将这些命令映射到实例方法的方法。
set的语法是
```python
plt.setp(object or sequence, somestring, attribute)
```
如果使用对象调用,则设置调用:
```python
object.set_somestring(attribute)
```
如果使用序列调用则set
```python
for object in sequence:
object.set_somestring(attribute)
```
因此对于您的示例如果a是您的轴对象则可以执行以下操作
```python
a.set_xticklabels([])
a.set_yticklabels([])
a.set_xticks([])
a.set_yticks([])
```
![Pythonic Matplotlib示例](https://matplotlib.org/_images/sphx_glr_pythonic_matplotlib_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 1.0, 0.01)
fig, (ax1, ax2) = plt.subplots(2)
ax1.plot(t, np.sin(2*np.pi * t))
ax1.grid(True)
ax1.set_ylim((-2, 2))
ax1.set_ylabel('1 Hz')
ax1.set_title('A sine wave or two')
ax1.xaxis.set_tick_params(labelcolor='r')
ax2.plot(t, np.sin(2 * 2*np.pi * t))
ax2.grid(True)
ax2.set_ylim((-2, 2))
l = ax2.set_xlabel('Hi mom')
l.set_color('g')
l.set_fontsize('large')
plt.show()
```
## 下载这个示例
- [下载python源码: pythonic_matplotlib.py](https://matplotlib.org/_downloads/pythonic_matplotlib.py)
- [下载Jupyter notebook: pythonic_matplotlib.ipynb](https://matplotlib.org/_downloads/pythonic_matplotlib.ipynb)

View File

@@ -0,0 +1,61 @@
# 光栅化演示
![光栅化演示](https://matplotlib.org/_images/sphx_glr_rasterization_demo_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
d = np.arange(100).reshape(10, 10)
x, y = np.meshgrid(np.arange(11), np.arange(11))
theta = 0.25*np.pi
xx = x*np.cos(theta) - y*np.sin(theta)
yy = x*np.sin(theta) + y*np.cos(theta)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.set_aspect(1)
ax1.pcolormesh(xx, yy, d)
ax1.set_title("No Rasterization")
ax2.set_aspect(1)
ax2.set_title("Rasterization")
m = ax2.pcolormesh(xx, yy, d)
m.set_rasterized(True)
ax3.set_aspect(1)
ax3.pcolormesh(xx, yy, d)
ax3.text(0.5, 0.5, "Text", alpha=0.2,
va="center", ha="center", size=50, transform=ax3.transAxes)
ax3.set_title("No Rasterization")
ax4.set_aspect(1)
m = ax4.pcolormesh(xx, yy, d)
m.set_zorder(-20)
ax4.text(0.5, 0.5, "Text", alpha=0.2,
zorder=-15,
va="center", ha="center", size=50, transform=ax4.transAxes)
ax4.set_rasterization_zorder(-10)
ax4.set_title("Rasterization z$<-10$")
# ax2.title.set_rasterized(True) # should display a warning
plt.savefig("test_rasterization.pdf", dpi=150)
plt.savefig("test_rasterization.eps", dpi=150)
if not plt.rcParams["text.usetex"]:
plt.savefig("test_rasterization.svg", dpi=150)
# svg backend currently ignores the dpi
```
## 下载这个示例
- [下载python源码: rasterization_demo.py](https://matplotlib.org/_downloads/rasterization_demo.py)
- [下载Jupyter notebook: rasterization_demo.ipynb](https://matplotlib.org/_downloads/rasterization_demo.ipynb)

View File

@@ -0,0 +1,362 @@
# 设置和获取
pylot接口允许您使用setp和getp来设置和获取对象属性以及对象进行内省。
## 设置
要将线条的线型设置为虚线,您可以执行以下操作:
```python
>>> line, = plt.plot([1,2,3])
>>> plt.setp(line, linestyle='--')
```
如果要了解有效的参数类型,可以提供要设置的属性的名称而不使用值:
```python
>>> plt.setp(line, 'linestyle')
linestyle: [ '-' | '--' | '-.' | ':' | 'steps' | 'None' ]
```
如果要查看可以设置的所有属性及其可能的值,您可以执行以下操作:
```python
>>> plt.setp(line)
```
set在单个实例或实例列表上运行。如果您处于查询模式内省可能的值则仅使用序列中的第一个实例。实际设置值时全部
实例将被设置。 例如,假设您有两行的列表,以下将使两行变粗和变红:
```python
>>> x = np.arange(0,1.0,0.01)
>>> y1 = np.sin(2*np.pi*x)
>>> y2 = np.sin(4*np.pi*x)
>>> lines = plt.plot(x, y1, x, y2)
>>> plt.setp(lines, linewidth=2, color='r')
```
## 获取
get返回给定属性的值。 您可以使用get来查询单个属性的值
```python
>>> plt.getp(line, 'linewidth')
0.5
```
或所有属性/值对:
```python
>>> plt.getp(line)
aa = True
alpha = 1.0
antialiased = True
c = b
clip_on = True
color = b
... long listing skipped ...
```
## 别名
为了减少交互模式中的击键,许多属性具有短的别名,例如,'linew'为'lw''markeredgecolor'为'mec'。 当调用set或get in introspection模式时这些属性将被列为'fullname或aliasname'。
![别名](https://matplotlib.org/_images/sphx_glr_set_and_get_001.png)
输出:
```python
Line setters
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha: float
animated: bool
antialiased: bool
clip_box: `.Bbox`
clip_on: bool
clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
color: color
contains: callable
dash_capstyle: {'butt', 'round', 'projecting'}
dash_joinstyle: {'miter', 'round', 'bevel'}
dashes: sequence of floats (on/off ink in points) or (None, None)
drawstyle: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}
figure: `.Figure`
fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
gid: str
in_layout: bool
label: object
linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth: float
marker: unknown
markeredgecolor: color
markeredgewidth: float
markerfacecolor: color
markerfacecoloralt: color
markersize: float
markevery: unknown
path_effects: `.AbstractPathEffect`
picker: float or callable[[Artist, Event], Tuple[bool, dict]]
pickradius: float
rasterized: bool or None
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
solid_capstyle: {'butt', 'round', 'projecting'}
solid_joinstyle: {'miter', 'round', 'bevel'}
transform: matplotlib.transforms.Transform
url: str
visible: bool
xdata: 1D array
ydata: 1D array
zorder: float
Line getters
agg_filter = None
alpha = None
animated = False
antialiased = True
children = []
clip_box = TransformedBbox( Bbox(x0=0.0, y0=0.0, x1=1.0, ...
clip_on = True
clip_path = None
color = r
contains = None
dash_capstyle = butt
dash_joinstyle = round
data = (array([0. , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, ...
drawstyle = default
figure = Figure(640x480)
fillstyle = full
gid = None
in_layout = True
label = _line0
linestyle = --
linewidth = 2.0
marker = None
markeredgecolor = r
markeredgewidth = 1.0
markerfacecolor = r
markerfacecoloralt = none
markersize = 6.0
markevery = None
path = Path(array([[ 0.00000000e+00, 0.00000000e+00], ...
path_effects = []
picker = None
pickradius = 5
rasterized = None
sketch_params = None
snap = None
solid_capstyle = projecting
solid_joinstyle = round
transform = CompositeGenericTransform( TransformWrapper( ...
transformed_clip_path_and_affine = (None, None)
url = None
visible = True
xdata = [0. 0.01 0.02 0.03 0.04 0.05]...
xydata = [[0. 0. ] [0.01 0.06279052] ...
ydata = [0. 0.06279052 0.12533323 0.18738131 0.248...
zorder = 2
Rectangle setters
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha: float or None
animated: bool
antialiased: unknown
capstyle: {'butt', 'round', 'projecting'}
clip_box: `.Bbox`
clip_on: bool
clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
color: color
contains: callable
edgecolor: color or None or 'auto'
facecolor: color or None
figure: `.Figure`
fill: bool
gid: str
hatch: {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
height: unknown
in_layout: bool
joinstyle: {'miter', 'round', 'bevel'}
label: object
linestyle: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
linewidth: float or None for default
path_effects: `.AbstractPathEffect`
picker: None or bool or float or callable
rasterized: bool or None
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
transform: `.Transform`
url: str
visible: bool
width: unknown
x: unknown
xy: (float, float)
y: unknown
zorder: float
Rectangle getters
agg_filter = None
alpha = None
animated = False
antialiased = True
bbox = Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0)
capstyle = butt
children = []
clip_box = None
clip_on = True
clip_path = None
contains = None
data_transform = BboxTransformTo( TransformedBbox( Bbox...
edgecolor = (0.0, 0.0, 0.0, 0.0)
extents = Bbox(x0=80.0, y0=52.8, x1=576.0, y1=422.4)
facecolor = (1.0, 1.0, 1.0, 1.0)
figure = Figure(640x480)
fill = True
gid = None
hatch = None
height = 1.0
in_layout = True
joinstyle = miter
label =
linestyle = solid
linewidth = 0.0
patch_transform = CompositeGenericTransform( BboxTransformTo( ...
path = Path(array([[0., 0.], [1., 0.], [1.,...
path_effects = []
picker = None
rasterized = None
sketch_params = None
snap = None
transform = CompositeGenericTransform( CompositeGenericTra...
transformed_clip_path_and_affine = (None, None)
url = None
verts = [[ 80. 52.8] [576. 52.8] [576. 422.4] [ 80...
visible = True
width = 1.0
window_extent = Bbox(x0=80.0, y0=52.8, x1=576.0, y1=422.4)
x = 0.0
xy = (0.0, 0.0)
y = 0.0
zorder = 1
Text setters
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha: float
animated: bool
backgroundcolor: color
bbox: dict with properties for `.patches.FancyBboxPatch`
clip_box: `matplotlib.transforms.Bbox`
clip_on: bool
clip_path: { (`.path.Path`, `.transforms.Transform`), `.patches.Patch`, None }
color: color
contains: callable
figure: `.Figure`
fontfamily: {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontname: {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties: `.font_manager.FontProperties`
fontsize: {size in points, 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch: {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle: {'normal', 'italic', 'oblique'}
fontvariant: {'normal', 'small-caps'}
fontweight: {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid: str
horizontalalignment: {'center', 'right', 'left'}
in_layout: bool
label: object
linespacing: float (multiple of font size)
multialignment: {'left', 'right', 'center'}
path_effects: `.AbstractPathEffect`
picker: None or bool or float or callable
position: (float, float)
rasterized: bool or None
rotation: {angle in degrees, 'vertical', 'horizontal'}
rotation_mode: {None, 'default', 'anchor'}
sketch_params: (scale: float, length: float, randomness: float)
snap: bool or None
text: string or object castable to string (but ``None`` becomes ``''``)
transform: `.Transform`
url: str
usetex: bool or None
verticalalignment: {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible: bool
wrap: bool
x: float
y: float
zorder: float
Text getters
agg_filter = None
alpha = None
animated = False
bbox_patch = None
children = []
clip_box = None
clip_on = True
clip_path = None
color = black
contains = None
figure = Figure(640x480)
fontfamily = ['sans-serif']
fontname = DejaVu Sans
fontproperties = :family=sans-serif:style=normal:variant=normal:wei...
fontsize = 12.0
fontstyle = normal
fontvariant = normal
fontweight = normal
gid = None
horizontalalignment = center
in_layout = True
label =
path_effects = []
picker = None
position = (0.5, 1.0)
rasterized = None
rotation = 0.0
rotation_mode = None
sketch_params = None
snap = None
stretch = normal
text = Hi mom
transform = CompositeGenericTransform( BboxTransformTo( ...
transformed_clip_path_and_affine = (None, None)
unitless_position = (0.5, 1.0)
url = None
usetex = False
verticalalignment = baseline
visible = True
wrap = False
zorder = 3
```
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 1.0, 0.01)
y1 = np.sin(2*np.pi*x)
y2 = np.sin(4*np.pi*x)
lines = plt.plot(x, y1, x, y2)
l1, l2 = lines
plt.setp(lines, linestyle='--') # set both to dashed
plt.setp(l1, linewidth=2, color='r') # line1 is thick and red
plt.setp(l2, linewidth=1, color='g') # line2 is thinner and green
print('Line setters')
plt.setp(l1)
print('Line getters')
plt.getp(l1)
print('Rectangle setters')
plt.setp(plt.gca().patch)
print('Rectangle getters')
plt.getp(plt.gca().patch)
t = plt.title('Hi mom')
print('Text setters')
plt.setp(t)
print('Text getters')
plt.getp(t)
plt.show()
```
## 下载这个示例
- [下载python源码: set_and_get.py](https://matplotlib.org/_downloads/set_and_get.py)
- [下载Jupyter notebook: set_and_get.ipynb](https://matplotlib.org/_downloads/set_and_get.ipynb)

View File

@@ -0,0 +1,95 @@
# SVG过滤线
演示可能与mpl一起使用的SVG过滤效果。
请注意过滤效果仅在您的svg渲染器支持时才有效。
![SVG过滤线示例](https://matplotlib.org/_images/sphx_glr_svg_filter_line_001.png)
输出:
```python
Saving 'svg_filter_line.svg'
```
```python
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig1 = plt.figure()
ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
# draw lines
l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
mec="b", lw=5, ms=10, label="Line 1")
l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "rs-",
mec="r", lw=5, ms=10, color="r", label="Line 2")
for l in [l1, l2]:
# draw shadows with same lines with slight offset and gray colors.
xx = l.get_xdata()
yy = l.get_ydata()
shadow, = ax.plot(xx, yy)
shadow.update_from(l)
# adjust color
shadow.set_color("0.2")
# adjust zorder of the shadow lines so that it is drawn below the
# original lines
shadow.set_zorder(l.get_zorder() - 0.5)
# offset transform
ot = mtransforms.offset_copy(l.get_transform(), fig1,
x=4.0, y=-6.0, units='points')
shadow.set_transform(ot)
# set the id for a later use
shadow.set_gid(l.get_label() + "_shadow")
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
# save the figure as a bytes string in the svg format.
from io import BytesIO
f = BytesIO()
plt.savefig(f, format="svg")
import xml.etree.cElementTree as ET
# filter definition for a gaussian blur
filter_def = """
<defs xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<filter id='dropshadow' height='1.2' width='1.2'>
<feGaussianBlur result='blur' stdDeviation='3'/>
</filter>
</defs>
"""
# read in the saved svg
tree, xmlid = ET.XMLID(f.getvalue())
# insert the filter definition in the svg dom tree.
tree.insert(0, ET.XML(filter_def))
for l in [l1, l2]:
# pick up the svg element with given id
shadow = xmlid[l.get_label() + "_shadow"]
# apply shadow filter
shadow.set("filter", 'url(#dropshadow)')
fn = "svg_filter_line.svg"
print("Saving '%s'" % fn)
ET.ElementTree(tree).write(fn)
```
## 下载这个示例
- [下载python源码: svg_filter_line.py](https://matplotlib.org/_downloads/svg_filter_line.py)
- [下载Jupyter notebook: svg_filter_line.ipynb](https://matplotlib.org/_downloads/svg_filter_line.ipynb)

View File

@@ -0,0 +1,104 @@
# SVG过滤管道
演示可能与mpl一起使用的SVG过滤效果。饼图绘制代码借用了pie_demo.py
请注意过滤效果仅在您的svg渲染器支持时才有效。
![SVG过滤管道示例](https://matplotlib.org/_images/sphx_glr_svg_filter_pie_001.png)
输出:
```python
Saving 'svg_filter_pie.svg'
```
```python
import matplotlib.pyplot as plt
from matplotlib.patches import Shadow
# make a square figure and axes
fig1 = plt.figure(1, figsize=(6, 6))
ax = fig1.add_axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
# We want to draw the shadow for each pie but we will not use "shadow"
# option as it does'n save the references to the shadow patches.
pies = ax.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%')
for w in pies[0]:
# set the id with the label.
w.set_gid(w.get_label())
# we don't want to draw the edge of the pie
w.set_ec("none")
for w in pies[0]:
# create shadow patch
s = Shadow(w, -0.01, -0.01)
s.set_gid(w.get_gid() + "_shadow")
s.set_zorder(w.get_zorder() - 0.1)
ax.add_patch(s)
# save
from io import BytesIO
f = BytesIO()
plt.savefig(f, format="svg")
import xml.etree.cElementTree as ET
# filter definition for shadow using a gaussian blur
# and lightening effect.
# The lightening filter is copied from http://www.w3.org/TR/SVG/filters.html
# I tested it with Inkscape and Firefox3. "Gaussian blur" is supported
# in both, but the lightening effect only in the Inkscape. Also note
# that, Inkscape's exporting also may not support it.
filter_def = """
<defs xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'>
<filter id='dropshadow' height='1.2' width='1.2'>
<feGaussianBlur result='blur' stdDeviation='2'/>
</filter>
<filter id='MyFilter' filterUnits='objectBoundingBox' x='0' y='0' width='1' height='1'>
<feGaussianBlur in='SourceAlpha' stdDeviation='4%' result='blur'/>
<feOffset in='blur' dx='4%' dy='4%' result='offsetBlur'/>
<feSpecularLighting in='blur' surfaceScale='5' specularConstant='.75'
specularExponent='20' lighting-color='#bbbbbb' result='specOut'>
<fePointLight x='-5000%' y='-10000%' z='20000%'/>
</feSpecularLighting>
<feComposite in='specOut' in2='SourceAlpha' operator='in' result='specOut'/>
<feComposite in='SourceGraphic' in2='specOut' operator='arithmetic'
k1='0' k2='1' k3='1' k4='0'/>
</filter>
</defs>
"""
tree, xmlid = ET.XMLID(f.getvalue())
# insert the filter definition in the svg dom tree.
tree.insert(0, ET.XML(filter_def))
for i, pie_name in enumerate(labels):
pie = xmlid[pie_name]
pie.set("filter", 'url(#MyFilter)')
shadow = xmlid[pie_name + "_shadow"]
shadow.set("filter", 'url(#dropshadow)')
fn = "svg_filter_pie.svg"
print("Saving '%s'" % fn)
ET.ElementTree(tree).write(fn)
```
## 下载这个示例
- [下载python源码: svg_filter_pie.py](https://matplotlib.org/_downloads/svg_filter_pie.py)
- [下载Jupyter notebook: svg_filter_pie.ipynb](https://matplotlib.org/_downloads/svg_filter_pie.ipynb)

View File

@@ -0,0 +1,65 @@
# 表格演示
演示表函数以在图表中显示表格。
![表格演示示例](https://matplotlib.org/_images/sphx_glr_table_demo_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[139361, 331509, 343164, 781380, 52269]]
columns = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rows = ['%d year' % x for x in (100, 50, 20, 10, 5)]
values = np.arange(0, 2500, 500)
value_increment = 1000
# Get some pastel shades for the colors
colors = plt.cm.BuPu(np.linspace(0, 0.5, len(rows)))
n_rows = len(data)
index = np.arange(len(columns)) + 0.3
bar_width = 0.4
# Initialize the vertical-offset for the stacked bar chart.
y_offset = np.zeros(len(columns))
# Plot bars and create text labels for the table
cell_text = []
for row in range(n_rows):
plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row])
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x / 1000.0) for x in y_offset])
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
cell_text.reverse()
# Add a table at the bottom of the axes
the_table = plt.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
loc='bottom')
# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.2, bottom=0.2)
plt.ylabel("Loss in ${0}'s".format(value_increment))
plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])
plt.title('Loss by Disaster')
plt.show()
```
## 下载这个示例
- [下载python源码: table_demo.py](https://matplotlib.org/_downloads/table_demo.py)
- [下载Jupyter notebook: table_demo.ipynb](https://matplotlib.org/_downloads/table_demo.ipynb)

View File

@@ -0,0 +1,35 @@
# 严密的Bbox测试
![严密的Bbox测试示例](https://matplotlib.org/_images/sphx_glr_tight_bbox_test_001.png)
输出:
```python
saving tight_bbox_test.png
saving tight_bbox_test.pdf
saving tight_bbox_test.svg
saving tight_bbox_test.svgz
saving tight_bbox_test.eps
```
```python
import matplotlib.pyplot as plt
import numpy as np
ax = plt.axes([0.1, 0.3, 0.5, 0.5])
ax.pcolormesh(np.array([[1, 2], [3, 4]]))
plt.yticks([0.5, 1.5], ["long long tick label",
"tick label"])
plt.ylabel("My y-label")
plt.title("Check saved figures for their bboxes")
for ext in ["png", "pdf", "svg", "svgz", "eps"]:
print("saving tight_bbox_test.%s" % (ext,))
plt.savefig("tight_bbox_test.%s" % (ext,), bbox_inches="tight")
plt.show()
```
## 下载这个示例
- [下载python源码: tight_bbox_test.py](https://matplotlib.org/_downloads/tight_bbox_test.py)
- [下载Jupyter notebook: tight_bbox_test.ipynb](https://matplotlib.org/_downloads/tight_bbox_test.ipynb)

View File

@@ -0,0 +1,52 @@
# Transoffset
这说明了使用transforms.offset_copy进行变换该变换将绘图元素如文本字符串定位在屏幕坐标点或英寸中相对于任何坐标中给出的位置的指定偏移处。
每个Artist - 从中派生Text和Line等类的mpl类 - 都有一个可以在创建Artist时设置的转换例如通过相应的pyplot命令。 默认情况下这通常是Axes.transData转换从数据单元到屏幕点。 我们可以使用offset_copy函数来修改此转换的副本其中修改包含偏移量。
![Transoffset示例](https://matplotlib.org/_images/sphx_glr_transoffset_001.png)
```python
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import numpy as np
xs = np.arange(7)
ys = xs**2
fig = plt.figure(figsize=(5, 10))
ax = plt.subplot(2, 1, 1)
# If we want the same offset for each text instance,
# we only need to make one transform. To get the
# transform argument to offset_copy, we need to make the axes
# first; the subplot command above is one way to do this.
trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
x=0.05, y=0.10, units='inches')
for x, y in zip(xs, ys):
plt.plot((x,), (y,), 'ro')
plt.text(x, y, '%d, %d' % (int(x), int(y)), transform=trans_offset)
# offset_copy works for polar plots also.
ax = plt.subplot(2, 1, 2, projection='polar')
trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
y=6, units='dots')
for x, y in zip(xs, ys):
plt.polar((x,), (y,), 'ro')
plt.text(x, y, '%d, %d' % (int(x), int(y)),
transform=trans_offset,
horizontalalignment='center',
verticalalignment='bottom')
plt.show()
```
## 下载这个示例
- [下载python源码: transoffset.py](https://matplotlib.org/_downloads/transoffset.py)
- [下载Jupyter notebook: transoffset.ipynb](https://matplotlib.org/_downloads/transoffset.ipynb)

View File

@@ -0,0 +1,71 @@
# Zorder演示
轴的默认绘制顺序是补丁,线条,文本。 此顺序由zorder属性确定。 设置以下默认值
Artist | Z-order
---|---
Patch / PatchCollection | 1
Line2D / LineCollection | 2
Text | 3
您可以通过设置zorder来更改单个艺术家的顺序。任何单独的plot() 调用都可以为该特定项的zorder设置一个值。
在下面的第一个子图中,线条在散点图上方的补丁集合上方绘制,这是默认值。
在下面的子图中,顺序颠倒过来。
第二个图显示了如何控制各行的zorder。
```python
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.random(20)
y = np.random.random(20)
```
分散的顶部的线
```python
plt.figure()
plt.subplot(211)
plt.plot(x, y, 'C3', lw=3)
plt.scatter(x, y, s=120)
plt.title('Lines on top of dots')
# Scatter plot on top of lines
plt.subplot(212)
plt.plot(x, y, 'C3', zorder=1, lw=3)
plt.scatter(x, y, s=120, zorder=2)
plt.title('Dots on top of lines')
plt.tight_layout()
```
![Zorder演示](https://matplotlib.org/_images/sphx_glr_zorder_demo_001.png)
一个新的图像,带有单独订购的物品
```python
x = np.linspace(0, 2*np.pi, 100)
plt.rcParams['lines.linewidth'] = 10
plt.figure()
plt.plot(x, np.sin(x), label='zorder=10', zorder=10) # on top
plt.plot(x, np.sin(1.1*x), label='zorder=1', zorder=1) # bottom
plt.plot(x, np.sin(1.2*x), label='zorder=3', zorder=3)
plt.axhline(0, label='zorder=2', color='grey', zorder=2)
plt.title('Custom order of elements')
l = plt.legend(loc='upper right')
l.set_zorder(20) # put the legend on top
plt.show()
```
![Zorder演示2](https://matplotlib.org/_images/sphx_glr_zorder_demo_002.png)
## 下载这个示例
- [下载python源码: zorder_demo.py](https://matplotlib.org/_downloads/zorder_demo.py)
- [下载Jupyter notebook: zorder_demo.ipynb](https://matplotlib.org/_downloads/zorder_demo.ipynb)