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,101 @@
# 箭头指南
向图表添加箭头图像。
箭头通常用于注释图表。本教程介绍如何绘制在绘图上的数据限制发生更改时表现不同的箭头。通常,绘图上的点可以固定在“数据空间”或“显示空间”中。当数据限制被改变时,数据空间中绘制的东西会移动 - 散点图中的点就是一个例子。当数据限制被改变时,在显示空间中绘制的东西保持静止 - 例如图形标题或轴标签。
箭头由头部(可能是尾部)和在起点和终点之间绘制的杆组成,从现在开始称为“锚点”。 这里我们展示了绘制箭头的三个用例,具体取决于是否需要在数据或显示空间中修复头部或锚点:
1. 头部形状固定在显示空间中,锚点固定在数据空间中。
1. 头部形状和锚点固定在展示空间中。
1. 再数据空间中固定的整个图像补丁的程序
下面依次介绍每个用例。
```python
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
x_tail = 0.1
y_tail = 0.1
x_head = 0.9
y_head = 0.9
dx = x_head - x_tail
dy = y_head - y_tail
```
## 头部形状固定在显示空间中,锚点固定在数据空间中
如果要注释绘图,并且如果平移或缩放绘图,则不希望箭头更改形状或位置,这非常有用。请注意,当轴限制发生变化时。
在这种情况下,我们使用 [patches.FancyArrowPatch](https://matplotlib.org/api/_as_gen/matplotlib.patches.FancyArrowPatch.html#matplotlib.patches.FancyArrowPatch)。
请注意,更改轴限制时,箭头形状保持不变,但锚点会移动。
```python
fig, axs = plt.subplots(nrows=2)
arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy),
mutation_scale=100)
axs[0].add_patch(arrow)
arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy),
mutation_scale=100)
axs[1].add_patch(arrow)
axs[1].set_xlim(0, 2)
axs[1].set_ylim(0, 2)
```
![箭头指南示例](https://matplotlib.org/_images/sphx_glr_arrow_guide_001.png)
## 头部形状和锚点固定在展示空间中
如果要注释绘图,并且如果平移或缩放绘图,则不希望箭头更改形状或位置,这非常有用。
在这种情况下,我们使用 [patches.FancyArrowPatch](https://matplotlib.org/api/_as_gen/matplotlib.patches.FancyArrowPatch.html#matplotlib.patches.FancyArrowPatch) ,并传递关键字参数transform = ax.transAxes,其中ax是我们添加补丁的轴。
请注意,更改轴限制时,箭头形状和位置保持不变。
```python
fig, axs = plt.subplots(nrows=2)
arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy),
mutation_scale=100,
transform=axs[0].transAxes)
axs[0].add_patch(arrow)
arrow = mpatches.FancyArrowPatch((x_tail, y_tail), (dx, dy),
mutation_scale=100,
transform=axs[1].transAxes)
axs[1].add_patch(arrow)
axs[1].set_xlim(0, 2)
axs[1].set_ylim(0, 2)
```
![箭头指南2](https://matplotlib.org/_images/sphx_glr_arrow_guide_002.png)
## 头部形状和锚点固定在数据空间中
在这种情况下,我们使用 [patches.Arrow](https://matplotlib.org/api/_as_gen/matplotlib.patches.Arrow.html#matplotlib.patches.Arrow)
请注意,更改轴限制时,箭头形状和位置会发生变化。
```python
fig, axs = plt.subplots(nrows=2)
arrow = mpatches.Arrow(x_tail, y_tail, dx, dy)
axs[0].add_patch(arrow)
arrow = mpatches.Arrow(x_tail, y_tail, dx, dy)
axs[1].add_patch(arrow)
axs[1].set_xlim(0, 2)
axs[1].set_ylim(0, 2)
```
![箭头指南3](https://matplotlib.org/_images/sphx_glr_arrow_guide_003.png)
```python
plt.show()
```
## 下载这个示例
- [下载python源码: arrow_guide.py](https://matplotlib.org/_downloads/arrow_guide.py)
- [下载Jupyter notebook: arrow_guide.ipynb](https://matplotlib.org/_downloads/arrow_guide.ipynb)

View File

@@ -0,0 +1,132 @@
# matplotlib艺术家对象的参考
此示例显示使用matplotlib API绘制的几个matplotlib的图形基元(艺术家)。[艺术家对象API](https://matplotlib.org/api/artist_api.html#artist-api)提供完整的艺术家列表和文档。
Copyright (c) 2010, Bartosz Telenczuk BSD License
```python
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.path as mpath
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
def label(xy, text):
y = xy[1] - 0.15 # shift y-value for label so that it's below the artist
plt.text(xy[0], y, text, ha="center", family='sans-serif', size=14)
fig, ax = plt.subplots()
# create 3x3 grid to plot the artists
grid = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1).T
patches = []
# add a circle
circle = mpatches.Circle(grid[0], 0.1, ec="none")
patches.append(circle)
label(grid[0], "Circle")
# add a rectangle
rect = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none")
patches.append(rect)
label(grid[1], "Rectangle")
# add a wedge
wedge = mpatches.Wedge(grid[2], 0.1, 30, 270, ec="none")
patches.append(wedge)
label(grid[2], "Wedge")
# add a Polygon
polygon = mpatches.RegularPolygon(grid[3], 5, 0.1)
patches.append(polygon)
label(grid[3], "Polygon")
# add an ellipse
ellipse = mpatches.Ellipse(grid[4], 0.2, 0.1)
patches.append(ellipse)
label(grid[4], "Ellipse")
# add an arrow
arrow = mpatches.Arrow(grid[5, 0] - 0.05, grid[5, 1] - 0.05, 0.1, 0.1,
width=0.1)
patches.append(arrow)
label(grid[5], "Arrow")
# add a path patch
Path = mpath.Path
path_data = [
(Path.MOVETO, [0.018, -0.11]),
(Path.CURVE4, [-0.031, -0.051]),
(Path.CURVE4, [-0.115, 0.073]),
(Path.CURVE4, [-0.03, 0.073]),
(Path.LINETO, [-0.011, 0.039]),
(Path.CURVE4, [0.043, 0.121]),
(Path.CURVE4, [0.075, -0.005]),
(Path.CURVE4, [0.035, -0.027]),
(Path.CLOSEPOLY, [0.018, -0.11])]
codes, verts = zip(*path_data)
path = mpath.Path(verts + grid[6], codes)
patch = mpatches.PathPatch(path)
patches.append(patch)
label(grid[6], "PathPatch")
# add a fancy box
fancybox = mpatches.FancyBboxPatch(
grid[7] - [0.025, 0.05], 0.05, 0.1,
boxstyle=mpatches.BoxStyle("Round", pad=0.02))
patches.append(fancybox)
label(grid[7], "FancyBboxPatch")
# add a line
x, y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]])
line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3)
label(grid[8], "Line2D")
colors = np.linspace(0, 1, len(patches))
collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
collection.set_array(np.array(colors))
ax.add_collection(collection)
ax.add_line(line)
plt.axis('equal')
plt.axis('off')
plt.tight_layout()
plt.show()
```
![matplotlib艺术家对象的参考示例](https://matplotlib.org/_images/sphx_glr_artist_reference_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.path
matplotlib.path.Path
matplotlib.lines
matplotlib.lines.Line2D
matplotlib.patches
matplotlib.patches.Circle
matplotlib.patches.Ellipse
matplotlib.patches.Wedge
matplotlib.patches.Rectangle
matplotlib.patches.Arrow
matplotlib.patches.PathPatch
matplotlib.patches.FancyBboxPatch
matplotlib.patches.RegularPolygon
matplotlib.collections
matplotlib.collections.PatchCollection
matplotlib.cm.ScalarMappable.set_array
matplotlib.axes.Axes.add_collection
matplotlib.axes.Axes.add_line
```
## 下载这个示例
- [下载python源码: artist_reference.py](https://matplotlib.org/_downloads/artist_reference.py)
- [下载Jupyter notebook: artist_reference.ipynb](https://matplotlib.org/_downloads/artist_reference.ipynb)

View File

@@ -0,0 +1,140 @@
# 具有自动缩放功能的Line,Poly和RegularPoly Collection
对于前两个子图,我们将使用螺旋。它们的大小将以图表单位设置,而不是数据单位。它们的位置将通过使用LineCollection和PolyCollection的“偏移”和“transOffset”kwargs以数据单位设置。
第三个子图将生成正多边形,具有与前两个相同类型的缩放和定位。
最后一个子图说明了使用 “offsets =(xo,yo)”,即单个元组而不是元组列表来生成连续的偏移曲线,其中偏移量以数据单位给出。 此行为仅适用于LineCollection。
```python
import matplotlib.pyplot as plt
from matplotlib import collections, colors, transforms
import numpy as np
nverts = 50
npts = 100
# Make some spirals
r = np.arange(nverts)
theta = np.linspace(0, 2*np.pi, nverts)
xx = r * np.sin(theta)
yy = r * np.cos(theta)
spiral = np.column_stack([xx, yy])
# Fixing random state for reproducibility
rs = np.random.RandomState(19680801)
# Make some offsets
xyo = rs.randn(npts, 2)
# Make a list of colors cycling through the default series.
colors = [colors.to_rgba(c)
for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]
fig, axes = plt.subplots(2, 2)
fig.subplots_adjust(top=0.92, left=0.07, right=0.97,
hspace=0.3, wspace=0.3)
((ax1, ax2), (ax3, ax4)) = axes # unpack the axes
col = collections.LineCollection([spiral], offsets=xyo,
transOffset=ax1.transData)
trans = fig.dpi_scale_trans + transforms.Affine2D().scale(1.0/72.0)
col.set_transform(trans) # the points to pixels transform
# Note: the first argument to the collection initializer
# must be a list of sequences of x,y tuples; we have only
# one sequence, but we still have to put it in a list.
ax1.add_collection(col, autolim=True)
# autolim=True enables autoscaling. For collections with
# offsets like this, it is neither efficient nor accurate,
# but it is good enough to generate a plot that you can use
# as a starting point. If you know beforehand the range of
# x and y that you want to show, it is better to set them
# explicitly, leave out the autolim kwarg (or set it to False),
# and omit the 'ax1.autoscale_view()' call below.
# Make a transform for the line segments such that their size is
# given in points:
col.set_color(colors)
ax1.autoscale_view() # See comment above, after ax1.add_collection.
ax1.set_title('LineCollection using offsets')
# The same data as above, but fill the curves.
col = collections.PolyCollection([spiral], offsets=xyo,
transOffset=ax2.transData)
trans = transforms.Affine2D().scale(fig.dpi/72.0)
col.set_transform(trans) # the points to pixels transform
ax2.add_collection(col, autolim=True)
col.set_color(colors)
ax2.autoscale_view()
ax2.set_title('PolyCollection using offsets')
# 7-sided regular polygons
col = collections.RegularPolyCollection(
7, sizes=np.abs(xx) * 10.0, offsets=xyo, transOffset=ax3.transData)
trans = transforms.Affine2D().scale(fig.dpi / 72.0)
col.set_transform(trans) # the points to pixels transform
ax3.add_collection(col, autolim=True)
col.set_color(colors)
ax3.autoscale_view()
ax3.set_title('RegularPolyCollection using offsets')
# Simulate a series of ocean current profiles, successively
# offset by 0.1 m/s so that they form what is sometimes called
# a "waterfall" plot or a "stagger" plot.
nverts = 60
ncurves = 20
offs = (0.1, 0.0)
yy = np.linspace(0, 2*np.pi, nverts)
ym = np.max(yy)
xx = (0.2 + (ym - yy) / ym) ** 2 * np.cos(yy - 0.4) * 0.5
segs = []
for i in range(ncurves):
xxx = xx + 0.02*rs.randn(nverts)
curve = np.column_stack([xxx, yy * 100])
segs.append(curve)
col = collections.LineCollection(segs, offsets=offs)
ax4.add_collection(col, autolim=True)
col.set_color(colors)
ax4.autoscale_view()
ax4.set_title('Successive data offsets')
ax4.set_xlabel('Zonal velocity component (m/s)')
ax4.set_ylabel('Depth (m)')
# Reverse the y-axis so depth increases downward
ax4.set_ylim(ax4.get_ylim()[::-1])
plt.show()
```
![缩放功能示例](https://matplotlib.org/_images/sphx_glr_collections_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.figure.Figure
matplotlib.collections
matplotlib.collections.LineCollection
matplotlib.collections.RegularPolyCollection
matplotlib.axes.Axes.add_collection
matplotlib.axes.Axes.autoscale_view
matplotlib.transforms.Affine2D
matplotlib.transforms.Affine2D.scale
```
## 下载这个示例
- [下载python源码: collections.py](https://matplotlib.org/_downloads/collections.py)
- [下载Jupyter notebook: collections.ipynb](https://matplotlib.org/_downloads/collections.ipynb)

View File

@@ -0,0 +1,54 @@
# 复合路径
制作复合路径 - 在这种情况下是两个简单的多边形,一个矩形和一个三角形。使用 ``CLOSEPOLY`` 和 ``MOVETO`` 作为复合路径的不同部分。
```python
import numpy as np
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import matplotlib.pyplot as plt
vertices = []
codes = []
codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY]
vertices = [(1, 1), (1, 2), (2, 2), (2, 1), (0, 0)]
codes += [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]
vertices += [(4, 4), (5, 5), (5, 4), (0, 0)]
vertices = np.array(vertices, float)
path = Path(vertices, codes)
pathpatch = PathPatch(path, facecolor='None', edgecolor='green')
fig, ax = plt.subplots()
ax.add_patch(pathpatch)
ax.set_title('A compound path')
ax.autoscale_view()
plt.show()
```
![复合路径示例](https://matplotlib.org/_images/sphx_glr_compound_path_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.path
matplotlib.path.Path
matplotlib.patches
matplotlib.patches.PathPatch
matplotlib.axes.Axes.add_patch
matplotlib.axes.Axes.autoscale_view
```
## 下载这个示例
- [下载python源码: compound_path.py](https://matplotlib.org/_downloads/compound_path.py)
- [下载Jupyter notebook: compound_path.ipynb](https://matplotlib.org/_downloads/compound_path.ipynb)

View File

@@ -0,0 +1,123 @@
# 绘制海豚
此示例显示如何使用[Path](https://matplotlib.org/api/path_api.html#matplotlib.path.Path),[PathPatch](https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch)和[transforms](https://matplotlib.org/api/transformations.html#module-matplotlib.transforms)类绘制和操作给定顶点和节点的形状。
```python
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
r = np.random.rand(50)
t = np.random.rand(50) * np.pi * 2.0
x = r * np.cos(t)
y = r * np.sin(t)
fig, ax = plt.subplots(figsize=(6, 6))
circle = Circle((0, 0), 1, facecolor='none',
edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5)
ax.add_patch(circle)
im = plt.imshow(np.random.random((100, 100)),
origin='lower', cmap=cm.winter,
interpolation='spline36',
extent=([-1, 1, -1, 1]))
im.set_clip_path(circle)
plt.plot(x, y, 'o', color=(0.9, 0.9, 1.0), alpha=0.8)
# Dolphin from OpenClipart library by Andy Fitzsimon
# <cc:License rdf:about="http://web.resource.org/cc/PublicDomain">
# <cc:permits rdf:resource="http://web.resource.org/cc/Reproduction"/>
# <cc:permits rdf:resource="http://web.resource.org/cc/Distribution"/>
# <cc:permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/>
# </cc:License>
dolphin = """
M -0.59739425,160.18173 C -0.62740401,160.18885 -0.57867129,160.11183
-0.57867129,160.11183 C -0.57867129,160.11183 -0.5438361,159.89315
-0.39514638,159.81496 C -0.24645668,159.73678 -0.18316813,159.71981
-0.18316813,159.71981 C -0.18316813,159.71981 -0.10322971,159.58124
-0.057804323,159.58725 C -0.029723983,159.58913 -0.061841603,159.60356
-0.071265813,159.62815 C -0.080250183,159.65325 -0.082918513,159.70554
-0.061841203,159.71248 C -0.040763903,159.7194 -0.0066711426,159.71091
0.077336307,159.73612 C 0.16879567,159.76377 0.28380306,159.86448
0.31516668,159.91533 C 0.3465303,159.96618 0.5011127,160.1771
0.5011127,160.1771 C 0.63668998,160.19238 0.67763022,160.31259
0.66556395,160.32668 C 0.65339985,160.34212 0.66350443,160.33642
0.64907098,160.33088 C 0.63463742,160.32533 0.61309688,160.297
0.5789627,160.29339 C 0.54348657,160.28968 0.52329693,160.27674
0.50728856,160.27737 C 0.49060916,160.27795 0.48965803,160.31565
0.46114204,160.33673 C 0.43329696,160.35786 0.4570711,160.39871
0.43309565,160.40685 C 0.4105108,160.41442 0.39416631,160.33027
0.3954995,160.2935 C 0.39683269,160.25672 0.43807996,160.21522
0.44567915,160.19734 C 0.45327833,160.17946 0.27946869,159.9424
-0.061852613,159.99845 C -0.083965233,160.0427 -0.26176109,160.06683
-0.26176109,160.06683 C -0.30127962,160.07028 -0.21167141,160.09731
-0.24649368,160.1011 C -0.32642366,160.11569 -0.34521187,160.06895
-0.40622293,160.0819 C -0.467234,160.09485 -0.56738444,160.17461
-0.59739425,160.18173
"""
vertices = []
codes = []
parts = dolphin.split()
i = 0
code_map = {
'M': (Path.MOVETO, 1),
'C': (Path.CURVE4, 3),
'L': (Path.LINETO, 1)}
while i < len(parts):
code = parts[i]
path_code, npoints = code_map[code]
codes.extend([path_code] * npoints)
vertices.extend([[float(x) for x in y.split(',')] for y in
parts[i + 1:i + npoints + 1]])
i += npoints + 1
vertices = np.array(vertices, float)
vertices[:, 1] -= 160
dolphin_path = Path(vertices, codes)
dolphin_patch = PathPatch(dolphin_path, facecolor=(0.6, 0.6, 0.6),
edgecolor=(0.0, 0.0, 0.0))
ax.add_patch(dolphin_patch)
vertices = Affine2D().rotate_deg(60).transform(vertices)
dolphin_path2 = Path(vertices, codes)
dolphin_patch2 = PathPatch(dolphin_path2, facecolor=(0.5, 0.5, 0.5),
edgecolor=(0.0, 0.0, 0.0))
ax.add_patch(dolphin_patch2)
plt.show()
```
![绘制海豚示例](https://matplotlib.org/_images/sphx_glr_dolphin_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.path
matplotlib.path.Path
matplotlib.patches
matplotlib.patches.PathPatch
matplotlib.patches.Circle
matplotlib.axes.Axes.add_patch
matplotlib.transforms
matplotlib.transforms.Affine2D
matplotlib.transforms.Affine2D.rotate_deg
```
## 下载这个示例
- [下载python源码: dolphin.py](https://matplotlib.org/_downloads/dolphin.py)
- [下载Jupyter notebook: dolphin.ipynb](https://matplotlib.org/_downloads/dolphin.ipynb)

View File

@@ -0,0 +1,86 @@
# 绘制甜甜圈
Draw donuts (miam!) using [Path](https://matplotlib.org/api/path_api.html#matplotlib.path.Path)s and [PathPatches](https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch). This example shows the effect of the path's orientations in a compound path.
```python
import numpy as np
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
def wise(v):
if v == 1:
return "CCW"
else:
return "CW"
def make_circle(r):
t = np.arange(0, np.pi * 2.0, 0.01)
t = t.reshape((len(t), 1))
x = r * np.cos(t)
y = r * np.sin(t)
return np.hstack((x, y))
Path = mpath.Path
fig, ax = plt.subplots()
inside_vertices = make_circle(0.5)
outside_vertices = make_circle(1.0)
codes = np.ones(
len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
codes[0] = mpath.Path.MOVETO
for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):
# Concatenate the inside and outside subpaths together, changing their
# order as needed
vertices = np.concatenate((outside_vertices[::outside],
inside_vertices[::inside]))
# Shift the path
vertices[:, 0] += i * 2.5
# The codes will be all "LINETO" commands, except for "MOVETO"s at the
# beginning of each subpath
all_codes = np.concatenate((codes, codes))
# Create the Path object
path = mpath.Path(vertices, all_codes)
# Add plot it
patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black')
ax.add_patch(patch)
ax.annotate("Outside %s,\nInside %s" % (wise(outside), wise(inside)),
(i * 2.5, -1.5), va="top", ha="center")
ax.set_xlim(-2, 10)
ax.set_ylim(-3, 2)
ax.set_title('Mmm, donuts!')
ax.set_aspect(1.0)
plt.show()
```
![绘制甜甜圈示例](https://matplotlib.org/_images/sphx_glr_donut_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.path
matplotlib.path.Path
matplotlib.patches
matplotlib.patches.PathPatch
matplotlib.patches.Circle
matplotlib.axes.Axes.add_patch
matplotlib.axes.Axes.annotate
matplotlib.axes.Axes.set_aspect
matplotlib.axes.Axes.set_xlim
matplotlib.axes.Axes.set_ylim
matplotlib.axes.Axes.set_title
```
## 下载这个示例
- [下载python源码: donut.py](https://matplotlib.org/_downloads/donut.py)
- [下载Jupyter notebook: donut.ipynb](https://matplotlib.org/_downloads/donut.ipynb)

View File

@@ -0,0 +1,53 @@
# 椭圆集合
绘制椭圆的集合。虽然使用 [EllipseCollection](https://matplotlib.org/api/collections_api.html#matplotlib.collections.EllipseCollection) 或[PathCollection](https://matplotlib.org/api/collections_api.html#matplotlib.collections.PathCollection) 同样可行,但使用[EllipseCollection](https://matplotlib.org/api/collections_api.html#matplotlib.collections.EllipseCollection) 可以实现更短的代码。
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import EllipseCollection
x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)
XY = np.column_stack((X.ravel(), Y.ravel()))
ww = X / 10.0
hh = Y / 15.0
aa = X * 9
fig, ax = plt.subplots()
ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY,
transOffset=ax.transData)
ec.set_array((X + Y).ravel())
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()
```
![椭圆集合示例](https://matplotlib.org/_images/sphx_glr_ellipse_collection_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.collections
matplotlib.collections.EllipseCollection
matplotlib.axes.Axes.add_collection
matplotlib.axes.Axes.autoscale_view
matplotlib.cm.ScalarMappable.set_array
```
## 下载这个示例
- [下载python源码: ellipse_collection.py](https://matplotlib.org/_downloads/ellipse_collection.py)
- [下载Jupyter notebook: ellipse_collection.ipynb](https://matplotlib.org/_downloads/ellipse_collection.ipynb)

View File

@@ -0,0 +1,78 @@
# 椭圆演示
绘制多个椭圆。此处绘制单个椭圆。将其与[Ellipse集合示例](https://matplotlib.org/gallery/shapes_and_collections/ellipse_collection.html)进行比较。
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse
NUM = 250
ells = [Ellipse(xy=np.random.rand(2) * 10,
width=np.random.rand(), height=np.random.rand(),
angle=np.random.rand() * 360)
for i in range(NUM)]
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(np.random.rand())
e.set_facecolor(np.random.rand(3))
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.show()
```
![椭圆演示](https://matplotlib.org/_images/sphx_glr_ellipse_demo_001.png)
# 椭圆旋转
绘制许多不同角度的椭圆。
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse
delta = 45.0 # degrees
angles = np.arange(0, 360 + delta, delta)
ells = [Ellipse((1, 1), 4, 2, a) for a in angles]
a = plt.subplot(111, aspect='equal')
for e in ells:
e.set_clip_box(a.bbox)
e.set_alpha(0.1)
a.add_artist(e)
plt.xlim(-2, 4)
plt.ylim(-1, 3)
plt.show()
```
![椭圆演示2](https://matplotlib.org/_images/sphx_glr_ellipse_demo_002.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.patches
matplotlib.patches.Ellipse
matplotlib.axes.Axes.add_artist
matplotlib.artist.Artist.set_clip_box
matplotlib.artist.Artist.set_alpha
matplotlib.patches.Patch.set_facecolor
```
## 下载这个示例
- [下载python源码: ellipse_demo.py](https://matplotlib.org/_downloads/ellipse_demo.py)
- [下载Jupyter notebook: ellipse_demo.ipynb](https://matplotlib.org/_downloads/ellipse_demo.ipynb)

View File

@@ -0,0 +1,217 @@
# Fancybox演示
使用Matplotlib绘制精美的盒子。
以下示例显示如何绘制具有不同视觉属性的框。
```python
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import matplotlib.patches as mpatch
from matplotlib.patches import FancyBboxPatch
```
首先,我们将展示一些带有fancybox的样本盒。
```python
styles = mpatch.BoxStyle.get_styles()
spacing = 1.2
figheight = (spacing * len(styles) + .5)
fig1 = plt.figure(1, (4 / 1.5, figheight / 1.5))
fontsize = 0.3 * 72
for i, stylename in enumerate(sorted(styles)):
fig1.text(0.5, (spacing * (len(styles) - i) - 0.5) / figheight, stylename,
ha="center",
size=fontsize,
transform=fig1.transFigure,
bbox=dict(boxstyle=stylename, fc="w", ec="k"))
plt.show()
```
![Fancybox演示示例](https://matplotlib.org/_images/sphx_glr_fancybox_demo_001.png)
接下来,我们将同时展示多个精美的盒子。
```python
# Bbox object around which the fancy box will be drawn.
bb = mtransforms.Bbox([[0.3, 0.4], [0.7, 0.6]])
def draw_bbox(ax, bb):
# boxstyle=square with pad=0, i.e. bbox itself.
p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="square,pad=0.",
ec="k", fc="none", zorder=10.,
)
ax.add_patch(p_bbox)
def test1(ax):
# a fancy box with round corners. pad=0.1
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.1",
fc=(1., .8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
ax.text(0.1, 0.8,
r' boxstyle="round,pad=0.1"',
size=10, transform=ax.transAxes)
# draws control points for the fancy box.
# l = p_fancy.get_path().vertices
# ax.plot(l[:,0], l[:,1], ".")
# draw the original bbox in black
draw_bbox(ax, bb)
def test2(ax):
# bbox=round has two optional argument. pad and rounding_size.
# They can be set during the initialization.
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.1",
fc=(1., .8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
# boxstyle and its argument can be later modified with
# set_boxstyle method. Note that the old attributes are simply
# forgotten even if the boxstyle name is same.
p_fancy.set_boxstyle("round,pad=0.1, rounding_size=0.2")
# or
# p_fancy.set_boxstyle("round", pad=0.1, rounding_size=0.2)
ax.text(0.1, 0.8,
' boxstyle="round,pad=0.1\n rounding_size=0.2"',
size=10, transform=ax.transAxes)
# draws control points for the fancy box.
# l = p_fancy.get_path().vertices
# ax.plot(l[:,0], l[:,1], ".")
draw_bbox(ax, bb)
def test3(ax):
# mutation_scale determine overall scale of the mutation,
# i.e. both pad and rounding_size is scaled according to this
# value.
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.1",
mutation_scale=2.,
fc=(1., .8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
ax.text(0.1, 0.8,
' boxstyle="round,pad=0.1"\n mutation_scale=2',
size=10, transform=ax.transAxes)
# draws control points for the fancy box.
# l = p_fancy.get_path().vertices
# ax.plot(l[:,0], l[:,1], ".")
draw_bbox(ax, bb)
def test4(ax):
# When the aspect ratio of the axes is not 1, the fancy box may
# not be what you expected (green)
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.2",
fc="none",
ec=(0., .5, 0.), zorder=4)
ax.add_patch(p_fancy)
# You can compensate this by setting the mutation_aspect (pink).
p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
abs(bb.width), abs(bb.height),
boxstyle="round,pad=0.3",
mutation_aspect=.5,
fc=(1., 0.8, 1.),
ec=(1., 0.5, 1.))
ax.add_patch(p_fancy)
ax.text(0.1, 0.8,
' boxstyle="round,pad=0.3"\n mutation_aspect=.5',
size=10, transform=ax.transAxes)
draw_bbox(ax, bb)
def test_all():
plt.clf()
ax = plt.subplot(2, 2, 1)
test1(ax)
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.set_title("test1")
ax.set_aspect(1.)
ax = plt.subplot(2, 2, 2)
ax.set_title("test2")
test2(ax)
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.set_aspect(1.)
ax = plt.subplot(2, 2, 3)
ax.set_title("test3")
test3(ax)
ax.set_xlim(0., 1.)
ax.set_ylim(0., 1.)
ax.set_aspect(1)
ax = plt.subplot(2, 2, 4)
ax.set_title("test4")
test4(ax)
ax.set_xlim(-0.5, 1.5)
ax.set_ylim(0., 1.)
ax.set_aspect(2.)
plt.show()
test_all()
```
![Fancybox演示2](https://matplotlib.org/_images/sphx_glr_fancybox_demo_002.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.patches
matplotlib.patches.FancyBboxPatch
matplotlib.patches.BoxStyle
matplotlib.patches.BoxStyle.get_styles
matplotlib.transforms.Bbox
```
## 下载这个示例
- [下载python源码: fancybox_demo.py](https://matplotlib.org/_downloads/fancybox_demo.py)
- [下载Jupyter notebook: fancybox_demo.ipynb](https://matplotlib.org/_downloads/fancybox_demo.ipynb)

View File

@@ -0,0 +1,55 @@
# Hatch演示
目前仅在PS,PDF,SVG和Agg后端支持阴影线(图案填充多边形)。
```python
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
fig, (ax1, ax2, ax3) = plt.subplots(3)
ax1.bar(range(1, 5), range(1, 5), color='red', edgecolor='black', hatch="/")
ax1.bar(range(1, 5), [6] * 4, bottom=range(1, 5),
color='blue', edgecolor='black', hatch='//')
ax1.set_xticks([1.5, 2.5, 3.5, 4.5])
bars = ax2.bar(range(1, 5), range(1, 5), color='yellow', ecolor='black') + \
ax2.bar(range(1, 5), [6] * 4, bottom=range(1, 5),
color='green', ecolor='black')
ax2.set_xticks([1.5, 2.5, 3.5, 4.5])
patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')
for bar, pattern in zip(bars, patterns):
bar.set_hatch(pattern)
ax3.fill([1, 3, 3, 1], [1, 1, 2, 2], fill=False, hatch='\\')
ax3.add_patch(Ellipse((4, 1.5), 4, 0.5, fill=False, hatch='*'))
ax3.add_patch(Polygon([[0, 0], [4, 1.1], [6, 2.5], [2, 1.4]], closed=True,
fill=False, hatch='/'))
ax3.set_xlim((0, 6))
ax3.set_ylim((0, 2.5))
plt.show()
```
![Hatch演示](https://matplotlib.org/_images/sphx_glr_hatch_demo_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.patches
matplotlib.patches.Ellipse
matplotlib.patches.Polygon
matplotlib.axes.Axes.add_patch
matplotlib.patches.Patch.set_hatch
matplotlib.axes.Axes.bar
matplotlib.pyplot.bar
```
## 下载这个示例
- [下载python源码: hatch_demo.py](https://matplotlib.org/_downloads/hatch_demo.py)
- [下载Jupyter notebook: hatch_demo.ipynb](https://matplotlib.org/_downloads/hatch_demo.ipynb)

View File

@@ -0,0 +1,105 @@
# 线段集合
使用Matplotlib绘制线条。
[LineCollection](https://matplotlib.org/api/collections_api.html#matplotlib.collections.LineCollection) 允许在图上绘制多条线。 下面我们展示它的一些属性。
```python
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib import colors as mcolors
import numpy as np
# In order to efficiently plot many lines in a single set of axes,
# Matplotlib has the ability to add the lines all at once. Here is a
# simple example showing how it is done.
x = np.arange(100)
# Here are many sets of y to plot vs x
ys = x[:50, np.newaxis] + x[np.newaxis, :]
segs = np.zeros((50, 100, 2))
segs[:, :, 1] = ys
segs[:, :, 0] = x
# Mask some values to test masked array support:
segs = np.ma.masked_where((segs > 50) & (segs < 60), segs)
# We need to set the plot limits.
fig, ax = plt.subplots()
ax.set_xlim(x.min(), x.max())
ax.set_ylim(ys.min(), ys.max())
# colors is sequence of rgba tuples
# linestyle is a string or dash tuple. Legal string values are
# solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq)
# where onoffseq is an even length tuple of on and off ink in points.
# If linestyle is omitted, 'solid' is used
# See :class:`matplotlib.collections.LineCollection` for more information
colors = [mcolors.to_rgba(c)
for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]
line_segments = LineCollection(segs, linewidths=(0.5, 1, 1.5, 2),
colors=colors, linestyle='solid')
ax.add_collection(line_segments)
ax.set_title('Line collection with masked arrays')
plt.show()
```
![线段集合示例](https://matplotlib.org/_images/sphx_glr_line_collection_001.png)
为了在一组轴中有效地绘制多条线,Matplotlib能够一次性添加所有线。 这是一个简单的例子,展示了它是如何完成的。
```python
N = 50
x = np.arange(N)
# Here are many sets of y to plot vs x
ys = [x + i for i in x]
# We need to set the plot limits, they will not autoscale
fig, ax = plt.subplots()
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(ys), np.max(ys))
# colors is sequence of rgba tuples
# linestyle is a string or dash tuple. Legal string values are
# solid|dashed|dashdot|dotted. The dash tuple is (offset, onoffseq)
# where onoffseq is an even length tuple of on and off ink in points.
# If linestyle is omitted, 'solid' is used
# See :class:`matplotlib.collections.LineCollection` for more information
# Make a sequence of x,y pairs
line_segments = LineCollection([np.column_stack([x, y]) for y in ys],
linewidths=(0.5, 1, 1.5, 2),
linestyles='solid')
line_segments.set_array(x)
ax.add_collection(line_segments)
axcb = fig.colorbar(line_segments)
axcb.set_label('Line Number')
ax.set_title('Line Collection with mapped colors')
plt.sci(line_segments) # This allows interactive changing of the colormap.
plt.show()
```
![线段集合示例2](https://matplotlib.org/_images/sphx_glr_line_collection_002.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.collections
matplotlib.collections.LineCollection
matplotlib.cm.ScalarMappable.set_array
matplotlib.axes.Axes.add_collection
matplotlib.figure.Figure.colorbar
matplotlib.pyplot.colorbar
matplotlib.pyplot.sci
```
## 下载这个示例
- [下载python源码: line_collection.py](https://matplotlib.org/_downloads/line_collection.py)
- [下载Jupyter notebook: line_collection.ipynb](https://matplotlib.org/_downloads/line_collection.ipynb)

View File

@@ -0,0 +1,43 @@
# 标记路径
使用路径([path](https://matplotlib.org/api/path_api.html#matplotlib.path.Path))作为绘图的标记([plot](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot))。
```python
import matplotlib.pyplot as plt
import matplotlib.path as mpath
import numpy as np
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
verts = np.concatenate([circle.vertices, star.vertices[::-1, ...]])
codes = np.concatenate([circle.codes, star.codes])
cut_star = mpath.Path(verts, codes)
plt.plot(np.arange(10)**2, '--r', marker=cut_star, markersize=15)
plt.show()
```
![标记路径示例](https://matplotlib.org/_images/sphx_glr_marker_path_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.path
matplotlib.path.Path
matplotlib.path.Path.unit_regular_star
matplotlib.path.Path.unit_circle
matplotlib.axes.Axes.plot
matplotlib.pyplot.plot
```
## 下载这个示例
- [下载python源码: marker_path.py](https://matplotlib.org/_downloads/marker_path.py)
- [下载Jupyter notebook: marker_path.ipynb](https://matplotlib.org/_downloads/marker_path.ipynb)

View File

@@ -0,0 +1,78 @@
# 圆,楔和多边形
此示例演示如何使用修补程序集合。
```python
import numpy as np
from matplotlib.patches import Circle, Wedge, Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
resolution = 50 # the number of vertices
N = 3
x = np.random.rand(N)
y = np.random.rand(N)
radii = 0.1*np.random.rand(N)
patches = []
for x1, y1, r in zip(x, y, radii):
circle = Circle((x1, y1), r)
patches.append(circle)
x = np.random.rand(N)
y = np.random.rand(N)
radii = 0.1*np.random.rand(N)
theta1 = 360.0*np.random.rand(N)
theta2 = 360.0*np.random.rand(N)
for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2):
wedge = Wedge((x1, y1), r, t1, t2)
patches.append(wedge)
# Some limiting conditions on Wedge
patches += [
Wedge((.3, .7), .1, 0, 360), # Full circle
Wedge((.7, .8), .2, 0, 360, width=0.05), # Full ring
Wedge((.8, .3), .2, 0, 45), # Full sector
Wedge((.8, .3), .2, 45, 90, width=0.10), # Ring sector
]
for i in range(N):
polygon = Polygon(np.random.rand(N, 2), True)
patches.append(polygon)
colors = 100*np.random.rand(len(patches))
p = PatchCollection(patches, alpha=0.4)
p.set_array(np.array(colors))
ax.add_collection(p)
fig.colorbar(p, ax=ax)
plt.show()
```
![圆,楔和多边形示例](https://matplotlib.org/_images/sphx_glr_patch_collection_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.patches
matplotlib.patches.Circle
matplotlib.patches.Wedge
matplotlib.patches.Polygon
matplotlib.collections.PatchCollection
matplotlib.collections.Collection.set_array
matplotlib.axes.Axes.add_collection
matplotlib.figure.Figure.colorbar
```
## 下载这个示例
- [下载python源码: patch_collection.py](https://matplotlib.org/_downloads/patch_collection.py)
- [下载Jupyter notebook: patch_collection.ipynb](https://matplotlib.org/_downloads/patch_collection.ipynb)

View File

@@ -0,0 +1,57 @@
# PathPatch对象
此示例显示如何通过Matplotlib的API创建 [Path](https://matplotlib.org/api/path_api.html#matplotlib.path.Path) 和 [PathPatch](https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch) 对象。
```python
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
Path = mpath.Path
path_data = [
(Path.MOVETO, (1.58, -2.57)),
(Path.CURVE4, (0.35, -1.1)),
(Path.CURVE4, (-1.75, 2.0)),
(Path.CURVE4, (0.375, 2.0)),
(Path.LINETO, (0.85, 1.15)),
(Path.CURVE4, (2.2, 3.2)),
(Path.CURVE4, (3, 0.05)),
(Path.CURVE4, (2.0, -0.5)),
(Path.CLOSEPOLY, (1.58, -2.57)),
]
codes, verts = zip(*path_data)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
ax.add_patch(patch)
# plot control points and connecting lines
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')
ax.grid()
ax.axis('equal')
plt.show()
```
![PathPatch对象](https://matplotlib.org/_images/sphx_glr_path_patch_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.path
matplotlib.path.Path
matplotlib.patches
matplotlib.patches.PathPatch
matplotlib.axes.Axes.add_patch
```
## 下载这个示例
- [下载python源码: path_patch.py](https://matplotlib.org/_downloads/path_patch.py)
- [下载Jupyter notebook: path_patch.ipynb](https://matplotlib.org/_downloads/path_patch.ipynb)

View File

@@ -0,0 +1,43 @@
# Bezier曲线
此示例展示 [PathPatch](https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch) 对象以创建Bezier多曲线路径修补程序。
```python
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
Path = mpath.Path
fig, ax = plt.subplots()
pp1 = mpatches.PathPatch(
Path([(0, 0), (1, 0), (1, 1), (0, 0)],
[Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]),
fc="none", transform=ax.transData)
ax.add_patch(pp1)
ax.plot([0.75], [0.25], "ro")
ax.set_title('The red point should be on the path')
plt.show()
```
![Bezier曲线示例](https://matplotlib.org/_images/sphx_glr_quad_bezier_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.path
matplotlib.path.Path
matplotlib.patches
matplotlib.patches.PathPatch
matplotlib.axes.Axes.add_patch
```
## 下载这个示例
- [下载python源码: quad_bezier.py](https://matplotlib.org/_downloads/quad_bezier.py)
- [下载Jupyter notebook: quad_bezier.ipynb](https://matplotlib.org/_downloads/quad_bezier.ipynb)

View File

@@ -0,0 +1,39 @@
# 散点图
此示例展示了一个简单的散点图。
```python
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2 # 0 to 15 point radii
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
```
![散点图示例](https://matplotlib.org/_images/sphx_glr_scatter_001.png)
## 参考
此示例中显示了以下函数和方法的用法:
```python
import matplotlib
matplotlib.axes.Axes.scatter
matplotlib.pyplot.scatter
```
## 下载这个示例
- [下载python源码: scatter.py](https://matplotlib.org/_downloads/scatter.py)
- [下载Jupyter notebook: scatter.ipynb](https://matplotlib.org/_downloads/scatter.ipynb)