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,23 @@
# 锚定Box01
![锚定Box01示例](https://matplotlib.org/_images/sphx_glr_anchored_box01_001.png)
```python
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText
fig, ax = plt.subplots(figsize=(3, 3))
at = AnchoredText("Figure 1a",
prop=dict(size=15), frameon=True, loc='upper left')
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at)
plt.show()
```
## 下载这个示例
- [下载python源码: anchored_box01.py](https://matplotlib.org/_downloads/anchored_box01.py)
- [下载Jupyter notebook: anchored_box01.ipynb](https://matplotlib.org/_downloads/anchored_box01.ipynb)

View File

@@ -0,0 +1,28 @@
# 锚定Box02
![锚定Box02示例](https://matplotlib.org/_images/sphx_glr_anchored_box02_001.png)
```python
from matplotlib.patches import Circle
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea
fig, ax = plt.subplots(figsize=(3, 3))
ada = AnchoredDrawingArea(40, 20, 0, 0,
loc='upper right', pad=0., frameon=False)
p1 = Circle((10, 10), 10)
ada.drawing_area.add_artist(p1)
p2 = Circle((30, 10), 5, fc="r")
ada.drawing_area.add_artist(p2)
ax.add_artist(ada)
plt.show()
```
## 下载这个示例
- [下载python源码: anchored_box02.py](https://matplotlib.org/_downloads/anchored_box02.py)
- [下载Jupyter notebook: anchored_box02.ipynb](https://matplotlib.org/_downloads/anchored_box02.ipynb)

View File

@@ -0,0 +1,25 @@
# 锚定Box03
![锚定Box03示例](https://matplotlib.org/_images/sphx_glr_anchored_box03_001.png)
```python
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox
fig, ax = plt.subplots(figsize=(3, 3))
box = AnchoredAuxTransformBox(ax.transData, loc='upper left')
el = Ellipse((0, 0), width=0.1, height=0.4, angle=30) # in data coordinates!
box.drawing_area.add_artist(el)
ax.add_artist(box)
plt.show()
```
## 下载这个示例
- [下载python源码: anchored_box03.py](https://matplotlib.org/_downloads/anchored_box03.py)
- [下载Jupyter notebook: anchored_box03.ipynb](https://matplotlib.org/_downloads/anchored_box03.ipynb)

View File

@@ -0,0 +1,45 @@
# 锚定Box04
![锚定Box04示例](https://matplotlib.org/_images/sphx_glr_anchored_box04_001.png)
```python
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (AnchoredOffsetbox, DrawingArea, HPacker,
TextArea)
fig, ax = plt.subplots(figsize=(3, 3))
box1 = TextArea(" Test : ", textprops=dict(color="k"))
box2 = DrawingArea(60, 20, 0, 0)
el1 = Ellipse((10, 10), width=16, height=5, angle=30, fc="r")
el2 = Ellipse((30, 10), width=16, height=5, angle=170, fc="g")
el3 = Ellipse((50, 10), width=16, height=5, angle=230, fc="b")
box2.add_artist(el1)
box2.add_artist(el2)
box2.add_artist(el3)
box = HPacker(children=[box1, box2],
align="center",
pad=0, sep=5)
anchored_box = AnchoredOffsetbox(loc='lower left',
child=box, pad=0.,
frameon=True,
bbox_to_anchor=(0., 1.02),
bbox_transform=ax.transAxes,
borderpad=0.,
)
ax.add_artist(anchored_box)
fig.subplots_adjust(top=0.8)
plt.show()
```
## 下载这个示例
- [下载python源码: anchored_box04.py](https://matplotlib.org/_downloads/anchored_box04.py)
- [下载Jupyter notebook: anchored_box04.ipynb](https://matplotlib.org/_downloads/anchored_box04.ipynb)

View File

@@ -0,0 +1,87 @@
# 注释说明
![注释说明示例](https://matplotlib.org/_images/sphx_glr_annotate_explain_001.png)
```python
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig, axs = plt.subplots(2, 2)
x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7
ax = axs.flat[0]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="-",
color="0.5",
patchB=None,
shrinkB=0,
connectionstyle="arc3,rad=0.3",
),
)
ax.text(.05, .95, "connect", transform=ax.transAxes, ha="left", va="top")
ax = axs.flat[1]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="-",
color="0.5",
patchB=el,
shrinkB=0,
connectionstyle="arc3,rad=0.3",
),
)
ax.text(.05, .95, "clip", transform=ax.transAxes, ha="left", va="top")
ax = axs.flat[2]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="-",
color="0.5",
patchB=el,
shrinkB=5,
connectionstyle="arc3,rad=0.3",
),
)
ax.text(.05, .95, "shrink", transform=ax.transAxes, ha="left", va="top")
ax = axs.flat[3]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="fancy",
color="0.5",
patchB=el,
shrinkB=5,
connectionstyle="arc3,rad=0.3",
),
)
ax.text(.05, .95, "mutate", transform=ax.transAxes, ha="left", va="top")
for ax in axs.flat:
ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_explain.py](https://matplotlib.org/_downloads/annotate_explain.py)
- [下载Jupyter notebook: annotate_explain.ipynb](https://matplotlib.org/_downloads/annotate_explain.ipynb)

View File

@@ -0,0 +1,24 @@
# 注释Simple01
![注释Simple01示例](https://matplotlib.org/_images/sphx_glr_annotate_simple01_001.png)
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(3, 3))
ax.annotate("",
xy=(0.2, 0.2), xycoords='data',
xytext=(0.8, 0.8), textcoords='data',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3"),
)
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_simple01.py](https://matplotlib.org/_downloads/annotate_simple01.py)
- [下载Jupyter notebook: annotate_simple01.ipynb](https://matplotlib.org/_downloads/annotate_simple01.ipynb)

View File

@@ -0,0 +1,25 @@
# 注释Simple02
![注释Simple02示例](https://matplotlib.org/_images/sphx_glr_annotate_simple02_001.png)
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(3, 3))
ax.annotate("Test",
xy=(0.2, 0.2), xycoords='data',
xytext=(0.8, 0.8), textcoords='data',
size=20, va="center", ha="center",
arrowprops=dict(arrowstyle="simple",
connectionstyle="arc3,rad=-0.2"),
)
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_simple02.py](https://matplotlib.org/_downloads/annotate_simple02.py)
- [下载Jupyter notebook: annotate_simple02.ipynb](https://matplotlib.org/_downloads/annotate_simple02.ipynb)

View File

@@ -0,0 +1,27 @@
# 注释Simple03
![注释Simple03示例](https://matplotlib.org/_images/sphx_glr_annotate_simple03_001.png)
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(3, 3))
ann = ax.annotate("Test",
xy=(0.2, 0.2), xycoords='data',
xytext=(0.8, 0.8), textcoords='data',
size=20, va="center", ha="center",
bbox=dict(boxstyle="round4", fc="w"),
arrowprops=dict(arrowstyle="-|>",
connectionstyle="arc3,rad=-0.2",
fc="w"),
)
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_simple03.py](https://matplotlib.org/_downloads/annotate_simple03.py)
- [下载Jupyter notebook: annotate_simple03.ipynb](https://matplotlib.org/_downloads/annotate_simple03.ipynb)

View File

@@ -0,0 +1,39 @@
# 注释Simple04
![注释Simple04示例](https://matplotlib.org/_images/sphx_glr_annotate_simple04_001.png)
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(3, 3))
ann = ax.annotate("Test",
xy=(0.2, 0.2), xycoords='data',
xytext=(0.8, 0.8), textcoords='data',
size=20, va="center", ha="center",
bbox=dict(boxstyle="round4", fc="w"),
arrowprops=dict(arrowstyle="-|>",
connectionstyle="arc3,rad=0.2",
relpos=(0., 0.),
fc="w"),
)
ann = ax.annotate("Test",
xy=(0.2, 0.2), xycoords='data',
xytext=(0.8, 0.8), textcoords='data',
size=20, va="center", ha="center",
bbox=dict(boxstyle="round4", fc="w"),
arrowprops=dict(arrowstyle="-|>",
connectionstyle="arc3,rad=-0.2",
relpos=(1., 0.),
fc="w"),
)
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_simple04.py](https://matplotlib.org/_downloads/annotate_simple04.py)
- [下载Jupyter notebook: annotate_simple04.ipynb](https://matplotlib.org/_downloads/annotate_simple04.ipynb)

View File

@@ -0,0 +1,24 @@
# 简单Coord01注释示例
![简单Coord01注释示例](https://matplotlib.org/_images/sphx_glr_annotate_simple_coord01_001.png)
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(3, 2))
an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xycoords="data",
va="center", ha="center",
bbox=dict(boxstyle="round", fc="w"))
an2 = ax.annotate("Test 2", xy=(1, 0.5), xycoords=an1,
xytext=(30, 0), textcoords="offset points",
va="center", ha="left",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_simple_coord01.py](https://matplotlib.org/_downloads/annotate_simple_coord01.py)
- [下载Jupyter notebook: annotate_simple_coord01.ipynb](https://matplotlib.org/_downloads/annotate_simple_coord01.ipynb)

View File

@@ -0,0 +1,27 @@
# 简单Coord02注释示例
![简单Coord02注释示例](https://matplotlib.org/_images/sphx_glr_annotate_simple_coord02_001.png)
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(3, 2))
an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xycoords="data",
va="center", ha="center",
bbox=dict(boxstyle="round", fc="w"))
an2 = ax.annotate("Test 2", xy=(0.5, 1.), xycoords=an1,
xytext=(0.5, 1.1), textcoords=(an1, "axes fraction"),
va="bottom", ha="center",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
fig.subplots_adjust(top=0.83)
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_simple_coord02.py](https://matplotlib.org/_downloads/annotate_simple_coord02.py)
- [下载Jupyter notebook: annotate_simple_coord02.ipynb](https://matplotlib.org/_downloads/annotate_simple_coord02.ipynb)

View File

@@ -0,0 +1,28 @@
# 简单Coord03注释示例
![简单Coord03注释示例](https://matplotlib.org/_images/sphx_glr_annotate_simple_coord03_001.png)
```python
import matplotlib.pyplot as plt
from matplotlib.text import OffsetFrom
fig, ax = plt.subplots(figsize=(3, 2))
an1 = ax.annotate("Test 1", xy=(0.5, 0.5), xycoords="data",
va="center", ha="center",
bbox=dict(boxstyle="round", fc="w"))
offset_from = OffsetFrom(an1, (0.5, 0))
an2 = ax.annotate("Test 2", xy=(0.1, 0.1), xycoords="data",
xytext=(0, -10), textcoords=offset_from,
# xytext is offset points from "xy=(0.5, 0), xycoords=an1"
va="top", ha="center",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_simple_coord03.py](https://matplotlib.org/_downloads/annotate_simple_coord03.py)
- [下载Jupyter notebook: annotate_simple_coord03.ipynb](https://matplotlib.org/_downloads/annotate_simple_coord03.ipynb)

View File

@@ -0,0 +1,42 @@
# 注释文本箭头
```python
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 5))
ax.set_aspect(1)
x1 = -1 + np.random.randn(100)
y1 = -1 + np.random.randn(100)
x2 = 1. + np.random.randn(100)
y2 = 1. + np.random.randn(100)
ax.scatter(x1, y1, color="r")
ax.scatter(x2, y2, color="g")
bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
ax.text(-2, -2, "Sample A", ha="center", va="center", size=20,
bbox=bbox_props)
ax.text(2, 2, "Sample B", ha="center", va="center", size=20,
bbox=bbox_props)
bbox_props = dict(boxstyle="rarrow", fc=(0.8, 0.9, 0.9), ec="b", lw=2)
t = ax.text(0, 0, "Direction", ha="center", va="center", rotation=45,
size=15,
bbox=bbox_props)
bb = t.get_bbox_patch()
bb.set_boxstyle("rarrow", pad=0.6)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
plt.show()
```
## 下载这个示例
- [下载python源码: annotate_text_arrow.py](https://matplotlib.org/_downloads/annotate_text_arrow.py)
- [下载Jupyter notebook: annotate_text_arrow.ipynb](https://matplotlib.org/_downloads/annotate_text_arrow.ipynb)

View File

@@ -0,0 +1,149 @@
# 色彩映射规范化
演示使用norm以非线性方式映射颜色映射。
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
```
Lognorm: Instead of pcolor log10(Z1) you can have colorbars that have
the exponential labels using a norm.
```python
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
# A low hump with a spike coming out of the top. Needs to have
# z/colour axis on a log scale so we see both hump and spike. linear
# scale only shows the spike.
Z1 = np.exp(-(X)**2 - (Y)**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
Z = Z1 + 50 * Z2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolor(X, Y, Z,
norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()),
cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')
```
![色彩映射规范化示例](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_001.png)
PowerNorm这是X中的幂律趋势部分遮蔽了Y中的整流正弦波。我们可以使用PowerNorm来消除幂律。
```python
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X**(2.)
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=1. / 2.),
cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')
pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')
```
![色彩映射规范化示例2](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_002.png)
SymLogNorm两个驼峰一个正面和一个正面正面具有5倍幅度。 线性地,你看不到负面的驼峰。 在这里,我们分别以对数方式对正负数据进行对数。
请注意,颜色条标签看起来不是很好。
```python
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = 5 * np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z1,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
pcm = ax[1].pcolormesh(X, Y, Z1, cmap='RdBu_r', vmin=-np.max(Z1))
fig.colorbar(pcm, ax=ax[1], extend='both')
```
![色彩映射规范化示例3](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_003.png)
自定义范例:自定义规范化的示例。这个使用上面的例子,并从负数标准化负数据。
```python
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
# Example of making your own norm. Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
#####
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=MidpointNormalize(midpoint=0.),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[1], extend='both')
```
![色彩映射规范化示例4](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_004.png)
常规颜色对于这一种颜色您提供了颜色的边界并且Norm将第一种颜色放在第一对之间第二种颜色放在第二对之间依此类推。
```python
fig, ax = plt.subplots(3, 1, figsize=(8, 8))
ax = ax.flatten()
# even bounds gives a contour-like effect
bounds = np.linspace(-1, 1, 10)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=norm,
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical')
# uneven bounds changes the colormapping:
bounds = np.array([-0.25, -0.125, 0, 0.5, 1])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[1].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical')
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z1))
fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical')
plt.show()
```
![色彩映射规范化示例5](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_005.png)
## 下载这个示例
- [下载python源码: colormap_normalizations.py](https://matplotlib.org/_downloads/colormap_normalizations.py)
- [下载Jupyter notebook: colormap_normalizations.ipynb](https://matplotlib.org/_downloads/colormap_normalizations.ipynb)

View File

@@ -0,0 +1,49 @@
# 色彩映射规范化边界
演示使用规范以非线性方式将颜色映射映射到数据上。
![色彩映射规范化边界示例](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_bounds_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
'''
BoundaryNorm: For this one you provide the boundaries for your colors,
and the Norm puts the first color in between the first pair, the
second color between the second pair, etc.
'''
fig, ax = plt.subplots(3, 1, figsize=(8, 8))
ax = ax.flatten()
# even bounds gives a contour-like effect
bounds = np.linspace(-1, 1, 10)
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=norm,
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both', orientation='vertical')
# uneven bounds changes the colormapping:
bounds = np.array([-0.25, -0.125, 0, 0.5, 1])
norm = colors.BoundaryNorm(boundaries=bounds, ncolors=256)
pcm = ax[1].pcolormesh(X, Y, Z, norm=norm, cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[1], extend='both', orientation='vertical')
pcm = ax[2].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[2], extend='both', orientation='vertical')
plt.show()
```
## 下载这个示例
- [下载python源码: colormap_normalizations_bounds.py](https://matplotlib.org/_downloads/colormap_normalizations_bounds.py)
- [下载Jupyter notebook: colormap_normalizations_bounds.ipynb](https://matplotlib.org/_downloads/colormap_normalizations_bounds.ipynb)

View File

@@ -0,0 +1,55 @@
# 色彩映射标准化自定义
演示使用规范以非线性方式将颜色映射映射到数据上。
![色彩映射标准化自定义示例](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_custom_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
N = 100
'''
Custom Norm: An example with a customized normalization. This one
uses the example above, and normalizes the negative data differently
from the positive.
'''
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
# Example of making your own norm. Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
#####
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=MidpointNormalize(midpoint=0.),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[1], extend='both')
plt.show()
```
## 下载这个示例
- [下载python源码: colormap_normalizations_custom.py](https://matplotlib.org/_downloads/colormap_normalizations_custom.py)
- [下载Jupyter notebook: colormap_normalizations_custom.ipynb](https://matplotlib.org/_downloads/colormap_normalizations_custom.ipynb)

View File

@@ -0,0 +1,40 @@
# 颜色映射规格化
演示使用规范以非线性方式将颜色映射映射到数据上。
![颜色映射规格化示例](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_lognorm_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
'''
Lognorm: Instead of pcolor log10(Z1) you can have colorbars that have
the exponential labels using a norm.
'''
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
# A low hump with a spike coming out of the top right. Needs to have
# z/colour axis on a log scale so we see both hump and spike. linear
# scale only shows the spike.
Z = np.exp(-X**2 - Y**2)
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolor(X, Y, Z,
norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()),
cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')
pcm = ax[1].pcolor(X, Y, Z, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')
plt.show()
```
## 下载这个示例
- [下载python源码: colormap_normalizations_lognorm.py](https://matplotlib.org/_downloads/colormap_normalizations_lognorm.py)
- [下载Jupyter notebook: colormap_normalizations_lognorm.ipynb](https://matplotlib.org/_downloads/colormap_normalizations_lognorm.ipynb)

View File

@@ -0,0 +1,37 @@
# 颜色映射规格化功能
演示使用规范以非线性方式将颜色映射映射到数据上。
![颜色映射规格化功能示例](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_power_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
'''
PowerNorm: Here a power-law trend in X partially obscures a rectified
sine wave in Y. We can remove the power law using a PowerNorm.
'''
X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)]
Z1 = (1 + np.sin(Y * 10.)) * X**(2.)
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=1./2.),
cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')
pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')
plt.show()
```
## 下载这个示例
- [下载python源码: colormap_normalizations_power.py](https://matplotlib.org/_downloads/colormap_normalizations_power.py)
- [下载Jupyter notebook: colormap_normalizations_power.ipynb](https://matplotlib.org/_downloads/colormap_normalizations_power.ipynb)

View File

@@ -0,0 +1,44 @@
# 色彩映射规范化Symlognorm
演示使用规范以非线性方式将颜色映射映射到数据上。
![色彩映射规范化Symlognorm示例](https://matplotlib.org/_images/sphx_glr_colormap_normalizations_symlognorm_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
"""
SymLogNorm: two humps, one negative and one positive, The positive
with 5-times the amplitude. Linearly, you cannot see detail in the
negative hump. Here we logarithmically scale the positive and
negative data separately.
Note that colorbar labels do not come out looking very good.
"""
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots(2, 1)
pcm = ax[0].pcolormesh(X, Y, Z,
norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
vmin=-1.0, vmax=1.0),
cmap='RdBu_r')
fig.colorbar(pcm, ax=ax[0], extend='both')
pcm = ax[1].pcolormesh(X, Y, Z, cmap='RdBu_r', vmin=-np.max(Z))
fig.colorbar(pcm, ax=ax[1], extend='both')
plt.show()
```
## 下载这个示例
- [下载python源码: colormap_normalizations_symlognorm.py](https://matplotlib.org/_downloads/colormap_normalizations_symlognorm.py)
- [下载Jupyter notebook: colormap_normalizations_symlognorm.ipynb](https://matplotlib.org/_downloads/colormap_normalizations_symlognorm.ipynb)

View File

@@ -0,0 +1,40 @@
# 连接简单例子01
![连接简单例子01示例](https://matplotlib.org/_images/sphx_glr_connect_simple01_001.png)
```python
from matplotlib.patches import ConnectionPatch
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 3))
xyA = (0.2, 0.2)
xyB = (0.8, 0.8)
coordsA = "data"
coordsB = "data"
con = ConnectionPatch(xyA, xyB, coordsA, coordsB,
arrowstyle="-|>", shrinkA=5, shrinkB=5,
mutation_scale=20, fc="w")
ax1.plot([xyA[0], xyB[0]], [xyA[1], xyB[1]], "o")
ax1.add_artist(con)
xy = (0.3, 0.2)
coordsA = "data"
coordsB = "data"
con = ConnectionPatch(xyA=xy, xyB=xy, coordsA=coordsA, coordsB=coordsB,
axesA=ax2, axesB=ax1,
arrowstyle="->", shrinkB=5)
ax2.add_artist(con)
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
ax2.set_xlim(0, .5)
ax2.set_ylim(0, .5)
plt.show()
```
## 下载这个示例
- [下载python源码: connect_simple01.py](https://matplotlib.org/_downloads/connect_simple01.py)
- [下载Jupyter notebook: connect_simple01.ipynb](https://matplotlib.org/_downloads/connect_simple01.ipynb)

View File

@@ -0,0 +1,60 @@
# 连接样式演示
![连接样式演示](https://matplotlib.org/_images/sphx_glr_connectionstyle_demo_001.png)
```python
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 5, figsize=(8, 4.8))
x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7
def demo_con_style(ax, connectionstyle, label=None):
x1, y1 = 0.3, 0.2
x2, y2 = 0.8, 0.6
ax.plot([x1, x2], [y1, y2], ".")
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="->",
color="0.5",
shrinkA=5, shrinkB=5,
patchA=None,
patchB=None,
connectionstyle=connectionstyle,
),
)
ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
transform=ax.transAxes, ha="left", va="top")
demo_con_style(axs[0, 0], "angle3,angleA=90,angleB=0")
demo_con_style(axs[1, 0], "angle3,angleA=0,angleB=90")
demo_con_style(axs[0, 1], "arc3,rad=0.")
demo_con_style(axs[1, 1], "arc3,rad=0.3")
demo_con_style(axs[2, 1], "arc3,rad=-0.3")
demo_con_style(axs[0, 2], "angle,angleA=-90,angleB=180,rad=0")
demo_con_style(axs[1, 2], "angle,angleA=-90,angleB=180,rad=5")
demo_con_style(axs[2, 2], "angle,angleA=-90,angleB=10,rad=5")
demo_con_style(axs[0, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0")
demo_con_style(axs[1, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5")
demo_con_style(axs[2, 3], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
demo_con_style(axs[0, 4], "bar,fraction=0.3")
demo_con_style(axs[1, 4], "bar,fraction=-0.3")
demo_con_style(axs[2, 4], "bar,angle=180,fraction=-0.2")
for ax in axs.flat:
ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
fig.tight_layout(pad=0)
plt.show()
```
## 下载这个示例
- [下载python源码: connectionstyle_demo.py](https://matplotlib.org/_downloads/connectionstyle_demo.py)
- [下载Jupyter notebook: connectionstyle_demo.ipynb](https://matplotlib.org/_downloads/connectionstyle_demo.ipynb)

View File

@@ -0,0 +1,60 @@
# 自定义Boxstyle01
![自定义Boxstyle01示例](https://matplotlib.org/_images/sphx_glr_custom_boxstyle01_001.png)
```python
from matplotlib.path import Path
def custom_box_style(x0, y0, width, height, mutation_size, mutation_aspect=1):
"""
Given the location and size of the box, return the path of
the box around it.
- *x0*, *y0*, *width*, *height* : location and size of the box
- *mutation_size* : a reference scale for the mutation.
- *aspect_ratio* : aspect-ration for the mutation.
"""
# note that we are ignoring mutation_aspect. This is okay in general.
# padding
mypad = 0.3
pad = mutation_size * mypad
# width and height with padding added.
width = width + 2 * pad
height = height + 2 * pad
# boundary of the padded box
x0, y0 = x0 - pad, y0 - pad
x1, y1 = x0 + width, y0 + height
cp = [(x0, y0),
(x1, y0), (x1, y1), (x0, y1),
(x0-pad, (y0+y1)/2.), (x0, y0),
(x0, y0)]
com = [Path.MOVETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO,
Path.CLOSEPOLY]
path = Path(cp, com)
return path
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(3, 3))
ax.text(0.5, 0.5, "Test", size=30, va="center", ha="center",
bbox=dict(boxstyle=custom_box_style, alpha=0.2))
plt.show()
```
## 下载这个示例
- [下载python源码: custom_boxstyle01.py](https://matplotlib.org/_downloads/custom_boxstyle01.py)
- [下载Jupyter notebook: custom_boxstyle01.ipynb](https://matplotlib.org/_downloads/custom_boxstyle01.ipynb)

View File

@@ -0,0 +1,85 @@
# 自定义Boxstyle02
![自定义Boxstyle02示例](https://matplotlib.org/_images/sphx_glr_custom_boxstyle02_001.png)
```python
from matplotlib.path import Path
from matplotlib.patches import BoxStyle
import matplotlib.pyplot as plt
# we may derive from matplotlib.patches.BoxStyle._Base class.
# You need to override transmute method in this case.
class MyStyle(BoxStyle._Base):
"""
A simple box.
"""
def __init__(self, pad=0.3):
"""
The arguments need to be floating numbers and need to have
default values.
*pad*
amount of padding
"""
self.pad = pad
super().__init__()
def transmute(self, x0, y0, width, height, mutation_size):
"""
Given the location and size of the box, return the path of
the box around it.
- *x0*, *y0*, *width*, *height* : location and size of the box
- *mutation_size* : a reference scale for the mutation.
Often, the *mutation_size* is the font size of the text.
You don't need to worry about the rotation as it is
automatically taken care of.
"""
# padding
pad = mutation_size * self.pad
# width and height with padding added.
width, height = width + 2.*pad, \
height + 2.*pad,
# boundary of the padded box
x0, y0 = x0-pad, y0-pad,
x1, y1 = x0+width, y0 + height
cp = [(x0, y0),
(x1, y0), (x1, y1), (x0, y1),
(x0-pad, (y0+y1)/2.), (x0, y0),
(x0, y0)]
com = [Path.MOVETO,
Path.LINETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.LINETO,
Path.CLOSEPOLY]
path = Path(cp, com)
return path
# register the custom style
BoxStyle._style_list["angled"] = MyStyle
fig, ax = plt.subplots(figsize=(3, 3))
ax.text(0.5, 0.5, "Test", size=30, va="center", ha="center", rotation=30,
bbox=dict(boxstyle="angled,pad=0.5", alpha=0.2))
del BoxStyle._style_list["angled"]
plt.show()
```
## 下载这个示例
- [下载python源码: custom_boxstyle02.py](https://matplotlib.org/_downloads/custom_boxstyle02.py)
- [下载Jupyter notebook: custom_boxstyle02.ipynb](https://matplotlib.org/_downloads/custom_boxstyle02.ipynb)

View File

@@ -0,0 +1,31 @@
# Gridspec演示01
![Gridspec演示01](https://matplotlib.org/_images/sphx_glr_demo_gridspec01_000.png)
```python
import matplotlib.pyplot as plt
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
ax.tick_params(labelbottom=False, labelleft=False)
fig = plt.figure(0)
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))
fig.suptitle("subplot2grid")
make_ticklabels_invisible(fig)
plt.show()
```
## 下载这个示例
- [下载python源码: demo_gridspec01.py](https://matplotlib.org/_downloads/demo_gridspec01.py)
- [下载Jupyter notebook: demo_gridspec01.ipynb](https://matplotlib.org/_downloads/demo_gridspec01.ipynb)

View File

@@ -0,0 +1,42 @@
# Gridspec演示03
![Gridspec演示03](https://matplotlib.org/_images/sphx_glr_demo_gridspec03_001.png)
```python
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
ax.tick_params(labelbottom=False, labelleft=False)
# demo 3 : gridspec with subplotpars set.
fig = plt.figure()
fig.suptitle("GridSpec w/ different subplotpars")
gs1 = GridSpec(3, 3)
gs1.update(left=0.05, right=0.48, wspace=0.05)
ax1 = plt.subplot(gs1[:-1, :])
ax2 = plt.subplot(gs1[-1, :-1])
ax3 = plt.subplot(gs1[-1, -1])
gs2 = GridSpec(3, 3)
gs2.update(left=0.55, right=0.98, hspace=0.05)
ax4 = plt.subplot(gs2[:, :-1])
ax5 = plt.subplot(gs2[:-1, -1])
ax6 = plt.subplot(gs2[-1, -1])
make_ticklabels_invisible(fig)
plt.show()
```
## 下载这个示例
- [下载python源码: demo_gridspec03.py](https://matplotlib.org/_downloads/demo_gridspec03.py)
- [下载Jupyter notebook: demo_gridspec03.ipynb](https://matplotlib.org/_downloads/demo_gridspec03.ipynb)

View File

@@ -0,0 +1,33 @@
# Gridspec演示05
![Gridspec演示05](https://matplotlib.org/_images/sphx_glr_demo_gridspec05_001.png)
```python
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def make_ticklabels_invisible(fig):
for i, ax in enumerate(fig.axes):
ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
ax.tick_params(labelbottom=False, labelleft=False)
f = plt.figure()
gs = gridspec.GridSpec(2, 2,
width_ratios=[1, 2], height_ratios=[4, 1])
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
ax4 = plt.subplot(gs[3])
make_ticklabels_invisible(f)
plt.show()
```
## 下载这个示例
- [下载python源码: demo_gridspec05.py](https://matplotlib.org/_downloads/demo_gridspec05.py)
- [下载Jupyter notebook: demo_gridspec05.ipynb](https://matplotlib.org/_downloads/demo_gridspec05.ipynb)

View File

@@ -0,0 +1,57 @@
# Gridspec演示06
![Gridspec演示06](https://matplotlib.org/_images/sphx_glr_demo_gridspec06_001.png)
```python
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from itertools import product
def squiggle_xy(a, b, c, d):
i = np.arange(0.0, 2*np.pi, 0.05)
return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d)
fig = plt.figure(figsize=(8, 8))
# gridspec inside gridspec
outer_grid = gridspec.GridSpec(4, 4, wspace=0.0, hspace=0.0)
for i in range(16):
inner_grid = gridspec.GridSpecFromSubplotSpec(3, 3,
subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
a = i // 4 + 1
b = i % 4 + 1
for j, (c, d) in enumerate(product(range(1, 4), repeat=2)):
ax = plt.Subplot(fig, inner_grid[j])
ax.plot(*squiggle_xy(a, b, c, d))
ax.set_xticks([])
ax.set_yticks([])
fig.add_subplot(ax)
all_axes = fig.get_axes()
#show only the outside spines
for ax in all_axes:
for sp in ax.spines.values():
sp.set_visible(False)
if ax.is_first_row():
ax.spines['top'].set_visible(True)
if ax.is_last_row():
ax.spines['bottom'].set_visible(True)
if ax.is_first_col():
ax.spines['left'].set_visible(True)
if ax.is_last_col():
ax.spines['right'].set_visible(True)
plt.show()
```
Total running time of the script: ( 0 minutes 2.041 seconds)
## 下载这个示例
- [下载python源码: demo_gridspec06.py](https://matplotlib.org/_downloads/demo_gridspec06.py)
- [下载Jupyter notebook: demo_gridspec06.ipynb](https://matplotlib.org/_downloads/demo_gridspec06.ipynb)

View File

@@ -0,0 +1,29 @@
# Pgf字体
![Pgf字体](https://matplotlib.org/_images/sphx_glr_pgf_fonts_001.png)
```python
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.family": "serif",
"font.serif": [], # use latex default serif font
"font.sans-serif": ["DejaVu Sans"], # use a specific sans-serif font
})
plt.figure(figsize=(4.5, 2.5))
plt.plot(range(5))
plt.text(0.5, 3., "serif")
plt.text(0.5, 2., "monospace", family="monospace")
plt.text(2.5, 2., "sans-serif", family="sans-serif")
plt.text(2.5, 1., "comic sans", family="Comic Sans MS")
plt.xlabel("µ is not $\\mu$")
plt.tight_layout(.5)
plt.savefig("pgf_fonts.pdf")
plt.savefig("pgf_fonts.png")
```
## 下载这个示例
- [下载python源码: pgf_fonts.py](https://matplotlib.org/_downloads/pgf_fonts.py)
- [下载Jupyter notebook: pgf_fonts.ipynb](https://matplotlib.org/_downloads/pgf_fonts.ipynb)

View File

@@ -0,0 +1,34 @@
# Pgf序言
```python
import matplotlib as mpl
mpl.use("pgf")
import matplotlib.pyplot as plt
plt.rcParams.update({
"font.family": "serif", # use serif/main font for text elements
"text.usetex": True, # use inline math for ticks
"pgf.rcfonts": False, # don't setup fonts from rc parameters
"pgf.preamble": [
"\\usepackage{units}", # load additional packages
"\\usepackage{metalogo}",
"\\usepackage{unicode-math}", # unicode math setup
r"\setmathfont{xits-math.otf}",
r"\setmainfont{DejaVu Serif}", # serif font via preamble
]
})
plt.figure(figsize=(4.5, 2.5))
plt.plot(range(5))
plt.xlabel("unicode text: я, ψ, €, ü, \\unitfrac[10]{°}{µm}")
plt.ylabel("\\XeLaTeX")
plt.legend(["unicode math: $λ=∑_i^∞ μ_i^2$"])
plt.tight_layout(.5)
plt.savefig("pgf_preamble.pdf")
plt.savefig("pgf_preamble.png")
```
## 下载这个示例
- [下载python源码: pgf_preamble_sgskip.py](https://matplotlib.org/_downloads/pgf_preamble_sgskip.py)
- [下载Jupyter notebook: pgf_preamble_sgskip.ipynb](https://matplotlib.org/_downloads/pgf_preamble_sgskip.ipynb)

View File

@@ -0,0 +1,31 @@
# Pgf文本系统
![Pgf文本系统示例](https://matplotlib.org/_images/sphx_glr_pgf_texsystem_001.png)
```python
import matplotlib.pyplot as plt
plt.rcParams.update({
"pgf.texsystem": "pdflatex",
"pgf.preamble": [
r"\usepackage[utf8x]{inputenc}",
r"\usepackage[T1]{fontenc}",
r"\usepackage{cmbright}",
]
})
plt.figure(figsize=(4.5, 2.5))
plt.plot(range(5))
plt.text(0.5, 3., "serif", family="serif")
plt.text(0.5, 2., "monospace", family="monospace")
plt.text(2.5, 2., "sans-serif", family="sans-serif")
plt.xlabel(r"µ is not $\mu$")
plt.tight_layout(.5)
plt.savefig("pgf_texsystem.pdf")
plt.savefig("pgf_texsystem.png")
```
## 下载这个示例
- [下载python源码: pgf_texsystem.py](https://matplotlib.org/_downloads/pgf_texsystem.py)
- [下载Jupyter notebook: pgf_texsystem.ipynb](https://matplotlib.org/_downloads/pgf_texsystem.ipynb)

View File

@@ -0,0 +1,93 @@
# 简单的Annotate01
![简单的Annotate01示例](https://matplotlib.org/_images/sphx_glr_simple_annotate01_001.png)
```python
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig, axs = plt.subplots(2, 4)
x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7
ax = axs.flat[0]
ax.plot([x1, x2], [y1, y2], "o")
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="->"))
ax.text(.05, .95, "A $->$ B", transform=ax.transAxes, ha="left", va="top")
ax = axs.flat[2]
ax.plot([x1, x2], [y1, y2], "o")
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0.3",
shrinkB=5)
)
ax.text(.05, .95, "shrinkB=5", transform=ax.transAxes, ha="left", va="top")
ax = axs.flat[3]
ax.plot([x1, x2], [y1, y2], "o")
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0.3"))
ax.text(.05, .95, "connectionstyle=arc3", transform=ax.transAxes, ha="left", va="top")
ax = axs.flat[4]
ax.plot([x1, x2], [y1, y2], "o")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.5)
ax.add_artist(el)
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0.2")
)
ax = axs.flat[5]
ax.plot([x1, x2], [y1, y2], "o")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.5)
ax.add_artist(el)
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0.2",
patchB=el)
)
ax.text(.05, .95, "patchB", transform=ax.transAxes, ha="left", va="top")
ax = axs.flat[6]
ax.plot([x1], [y1], "o")
ax.annotate("Test",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
ha="center", va="center",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->")
)
ax.text(.05, .95, "annotate", transform=ax.transAxes, ha="left", va="top")
ax = axs.flat[7]
ax.plot([x1], [y1], "o")
ax.annotate("Test",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
ha="center", va="center",
bbox=dict(boxstyle="round", fc="w", ),
arrowprops=dict(arrowstyle="->", relpos=(0., 0.))
)
ax.text(.05, .95, "relpos=(0,0)", transform=ax.transAxes, ha="left", va="top")
for ax in axs.flat:
ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
plt.show()
```
## 下载这个示例
- [下载python源码: simple_annotate01.py](https://matplotlib.org/_downloads/simple_annotate01.py)
- [下载Jupyter notebook: simple_annotate01.ipynb](https://matplotlib.org/_downloads/simple_annotate01.ipynb)

View File

@@ -0,0 +1,29 @@
# 简单的Legend01
![简单的Legend01示例](https://matplotlib.org/_images/sphx_glr_simple_legend01_001.png)
```python
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1, 2, 3], label="test1")
plt.plot([3, 2, 1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left',
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1, 2, 3], label="test1")
plt.plot([3, 2, 1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0.)
plt.show()
```
## 下载这个示例
- [下载python源码: simple_legend01.py](https://matplotlib.org/_downloads/simple_legend01.py)
- [下载Jupyter notebook: simple_legend01.ipynb](https://matplotlib.org/_downloads/simple_legend01.ipynb)

View File

@@ -0,0 +1,28 @@
# 简单的Legend02
![简单的Legend02示例](https://matplotlib.org/_images/sphx_glr_simple_legend02_001.png)
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line1, = ax.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = ax.plot([3, 2, 1], label="Line 2", linewidth=4)
# Create a legend for the first line.
first_legend = ax.legend(handles=[line1], loc='upper right')
# Add the legend manually to the current Axes.
ax.add_artist(first_legend)
# Create another legend for the second line.
ax.legend(handles=[line2], loc='lower right')
plt.show()
```
## 下载这个示例
- [下载python源码: simple_legend02.py](https://matplotlib.org/_downloads/simple_legend02.py)
- [下载Jupyter notebook: simple_legend02.ipynb](https://matplotlib.org/_downloads/simple_legend02.ipynb)