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,39 @@
# 在matplotlib中使用重音文本
Matplotlib通过tex、mathtext或unicode支持重音字符。
使用mathtext提供以下重音hatbrevegravebaracutetildevecdotddot。所有这些语法都具有相同的语法例如要创建一个overbar你可以使用 bar{o} 或者使用 o 元音来执行 ddot{o}。 还提供了快捷方式,例如: "o 'e `e ~n .x ^y
![绘制重音文本示例](https://matplotlib.org/_images/sphx_glr_accented_text_001.png)
![绘制重音文本示例2](https://matplotlib.org/_images/sphx_glr_accented_text_002.png)
```python
import matplotlib.pyplot as plt
# Mathtext demo
fig, ax = plt.subplots()
ax.plot(range(10))
ax.set_title(r'$\ddot{o}\acute{e}\grave{e}\hat{O}'
r'\breve{i}\bar{A}\tilde{n}\vec{q}$', fontsize=20)
# Shorthand is also supported and curly braces are optional
ax.set_xlabel(r"""$\"o\ddot o \'e\`e\~n\.x\^y$""", fontsize=20)
ax.text(4, 0.5, r"$F=m\ddot{x}$")
fig.tight_layout()
# Unicode demo
fig, ax = plt.subplots()
ax.set_title("GISCARD CHAHUTÉ À L'ASSEMBLÉE")
ax.set_xlabel("LE COUP DE DÉ DE DE GAULLE")
ax.set_ylabel('André was here!')
ax.text(0.2, 0.8, 'Institut für Festkörperphysik', rotation=45)
ax.text(0.4, 0.2, 'AVA (check kerning)')
plt.show()
```
## 下载这个示例
- [下载python源码: accented_text.py](https://matplotlib.org/_downloads/accented_text.py)
- [下载Jupyter notebook: accented_text.ipynb](https://matplotlib.org/_downloads/accented_text.ipynb)

View File

@@ -0,0 +1,392 @@
# 注释图
以下示例显示了如何在matplotlib中注释绘图。这包括突出显示特定的兴趣点并使用各种视觉工具来引起对这一点的关注。有关matplotlib中注释和文本工具的更完整和深入的描述请参阅[注释教程](https://matplotlib.org/tutorials/text/annotations.html)。
```python
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import numpy as np
from matplotlib.text import OffsetFrom
```
## 指定文本点和注释点
您必须指定注释点 xy = (x, y) 来注释此点。另外,您可以为此注释的文本位置指定文本点 xytext=(x, y)。 可选您可以使用xycoords和textcoords的以下字符串之一指定xy和xytext的坐标系默认为'data'
```python
'figure points' : points from the lower left corner of the figure
'figure pixels' : pixels from the lower left corner of the figure
'figure fraction' : 0,0 is lower left of figure and 1,1 is upper, right
'axes points' : points from lower left corner of axes
'axes pixels' : pixels from lower left corner of axes
'axes fraction' : 0,0 is lower left of axes and 1,1 is upper right
'offset points' : Specify an offset (in points) from the xy value
'offset pixels' : Specify an offset (in pixels) from the xy value
'data' : use the axes data coordinate system
```
注意:对于物理坐标系(点或像素),原点是图形或轴的(底部,左侧)。
(可选)您可以通过提供箭头属性字典来指定箭头属性,该属性可以从文本绘制和箭头到注释点
有效关键点是:
```python
width : the width of the arrow in points
frac : the fraction of the arrow length occupied by the head
headwidth : the width of the base of the arrow head in points
shrink : move the tip and base some percent away from the
annotated point and text
any key for matplotlib.patches.polygon (e.g., facecolor)
```
```python
# Create our figure and data we'll use for plotting
fig, ax = plt.subplots(figsize=(3, 3))
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
# Plot a line and add some simple annotations
line, = ax.plot(t, s)
ax.annotate('figure pixels',
xy=(10, 10), xycoords='figure pixels')
ax.annotate('figure points',
xy=(80, 80), xycoords='figure points')
ax.annotate('figure fraction',
xy=(.025, .975), xycoords='figure fraction',
horizontalalignment='left', verticalalignment='top',
fontsize=20)
# The following examples show off how these arrows are drawn.
ax.annotate('point offset from data',
xy=(2, 1), xycoords='data',
xytext=(-15, 25), textcoords='offset points',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='right', verticalalignment='bottom')
ax.annotate('axes fraction',
xy=(3, 1), xycoords='data',
xytext=(0.8, 0.95), textcoords='axes fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='right', verticalalignment='top')
# You may also use negative points or pixels to specify from (right, top).
# E.g., (-10, 10) is 10 points to the left of the right side of the axes and 10
# points above the bottom
ax.annotate('pixel offset from axes fraction',
xy=(1, 0), xycoords='axes fraction',
xytext=(-20, 20), textcoords='offset pixels',
horizontalalignment='right',
verticalalignment='bottom')
ax.set(xlim=(-1, 5), ylim=(-3, 5))
```
![注释图示例](https://matplotlib.org/_images/sphx_glr_annotation_demo_001.png)
## 使用多个坐标系和轴类型
您可以在不同位置和坐标系中指定xypoint和xytext也可以选择打开连接线并使用标记标记点。 注释也适用于极轴。
在下面的示例中xy点是本机坐标xycoords默认为'data'。对于极轴这是在θ半径空间中。示例中的文本放在小数字坐标系中。文本关键字args如水平和垂直对齐被尊重。
```python
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'), figsize=(3, 3))
r = np.arange(0, 1, 0.001)
theta = 2*2*np.pi*r
line, = ax.plot(theta, r)
ind = 800
thisr, thistheta = r[ind], theta[ind]
ax.plot([thistheta], [thisr], 'o')
ax.annotate('a polar annotation',
xy=(thistheta, thisr), # theta, radius
xytext=(0.05, 0.05), # fraction, fraction
textcoords='figure fraction',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='left',
verticalalignment='bottom')
# You can also use polar notation on a cartesian axes. Here the native
# coordinate system ('data') is cartesian, so you need to specify the
# xycoords and textcoords as 'polar' if you want to use (theta, radius).
el = Ellipse((0, 0), 10, 20, facecolor='r', alpha=0.5)
fig, ax = plt.subplots(subplot_kw=dict(aspect='equal'))
ax.add_artist(el)
el.set_clip_box(ax.bbox)
ax.annotate('the top',
xy=(np.pi/2., 10.), # theta, radius
xytext=(np.pi/3, 20.), # theta, radius
xycoords='polar',
textcoords='polar',
arrowprops=dict(facecolor='black', shrink=0.05),
horizontalalignment='left',
verticalalignment='bottom',
clip_on=True) # clip to the axes bounding box
ax.set(xlim=[-20, 20], ylim=[-20, 20])
```
![注释图示例2](https://matplotlib.org/_images/sphx_glr_annotation_demo_002.png)
![注释图示例3](https://matplotlib.org/_images/sphx_glr_annotation_demo_003.png)
## 自定义箭头和气泡样式
xytext和注释点之间的箭头以及覆盖注释文本的气泡可高度自定义。 下面是一些参数选项以及它们的结果输出。
```python
fig, ax = plt.subplots(figsize=(8, 5))
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=3)
ax.annotate('straight',
xy=(0, 1), xycoords='data',
xytext=(-50, 30), textcoords='offset points',
arrowprops=dict(arrowstyle="->"))
ax.annotate('arc3,\nrad 0.2',
xy=(0.5, -1), xycoords='data',
xytext=(-80, -60), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3,rad=.2"))
ax.annotate('arc,\nangle 50',
xy=(1., 1), xycoords='data',
xytext=(-90, 50), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc,angleA=0,armA=50,rad=10"))
ax.annotate('arc,\narms',
xy=(1.5, -1), xycoords='data',
xytext=(-80, -60), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc,angleA=0,armA=40,angleB=-90,armB=30,rad=7"))
ax.annotate('angle,\nangle 90',
xy=(2., 1), xycoords='data',
xytext=(-70, 30), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=90,rad=10"))
ax.annotate('angle3,\nangle -90',
xy=(2.5, -1), xycoords='data',
xytext=(-80, -60), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3,angleA=0,angleB=-90"))
ax.annotate('angle,\nround',
xy=(3., 1), xycoords='data',
xytext=(-60, 30), textcoords='offset points',
bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=90,rad=10"))
ax.annotate('angle,\nround4',
xy=(3.5, -1), xycoords='data',
xytext=(-70, -80), textcoords='offset points',
size=20,
bbox=dict(boxstyle="round4,pad=.5", fc="0.8"),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=-90,rad=10"))
ax.annotate('angle,\nshrink',
xy=(4., 1), xycoords='data',
xytext=(-60, 30), textcoords='offset points',
bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="->",
shrinkA=0, shrinkB=10,
connectionstyle="angle,angleA=0,angleB=90,rad=10"))
# You can pass an empty string to get only annotation arrows rendered
ann = ax.annotate('', xy=(4., 1.), xycoords='data',
xytext=(4.5, -1), textcoords='data',
arrowprops=dict(arrowstyle="<->",
connectionstyle="bar",
ec="k",
shrinkA=5, shrinkB=5))
ax.set(xlim=(-1, 5), ylim=(-4, 3))
# We'll create another figure so that it doesn't get too cluttered
fig, ax = plt.subplots()
el = Ellipse((2, -1), 0.5, 0.5)
ax.add_patch(el)
ax.annotate('$->$',
xy=(2., -1), xycoords='data',
xytext=(-150, -140), textcoords='offset points',
bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="->",
patchB=el,
connectionstyle="angle,angleA=90,angleB=0,rad=10"))
ax.annotate('arrow\nfancy',
xy=(2., -1), xycoords='data',
xytext=(-100, 60), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="fancy",
fc="0.6", ec="none",
patchB=el,
connectionstyle="angle3,angleA=0,angleB=-90"))
ax.annotate('arrow\nsimple',
xy=(2., -1), xycoords='data',
xytext=(100, 60), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="simple",
fc="0.6", ec="none",
patchB=el,
connectionstyle="arc3,rad=0.3"))
ax.annotate('wedge',
xy=(2., -1), xycoords='data',
xytext=(-100, -100), textcoords='offset points',
size=20,
# bbox=dict(boxstyle="round", fc="0.8"),
arrowprops=dict(arrowstyle="wedge,tail_width=0.7",
fc="0.6", ec="none",
patchB=el,
connectionstyle="arc3,rad=-0.3"))
ann = ax.annotate('bubble,\ncontours',
xy=(2., -1), xycoords='data',
xytext=(0, -70), textcoords='offset points',
size=20,
bbox=dict(boxstyle="round",
fc=(1.0, 0.7, 0.7),
ec=(1., .5, .5)),
arrowprops=dict(arrowstyle="wedge,tail_width=1.",
fc=(1.0, 0.7, 0.7), ec=(1., .5, .5),
patchA=None,
patchB=el,
relpos=(0.2, 0.8),
connectionstyle="arc3,rad=-0.1"))
ann = ax.annotate('bubble',
xy=(2., -1), xycoords='data',
xytext=(55, 0), textcoords='offset points',
size=20, va="center",
bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"),
arrowprops=dict(arrowstyle="wedge,tail_width=1.",
fc=(1.0, 0.7, 0.7), ec="none",
patchA=None,
patchB=el,
relpos=(0.2, 0.5)))
ax.set(xlim=(-1, 5), ylim=(-5, 3))
```
![注释图示例4](https://matplotlib.org/_images/sphx_glr_annotation_demo_005.png)
![注释图示例5](https://matplotlib.org/_images/sphx_glr_annotation_demo_005.png)
## 更多坐标系的例子
下面我们将展示几个坐标系的例子,以及如何指定注释的位置。
```python
fig, (ax1, ax2) = plt.subplots(1, 2)
bbox_args = dict(boxstyle="round", fc="0.8")
arrow_args = dict(arrowstyle="->")
# Here we'll demonstrate the extents of the coordinate system and how
# we place annotating text.
ax1.annotate('figure fraction : 0, 0', xy=(0, 0), xycoords='figure fraction',
xytext=(20, 20), textcoords='offset points',
ha="left", va="bottom",
bbox=bbox_args,
arrowprops=arrow_args)
ax1.annotate('figure fraction : 1, 1', xy=(1, 1), xycoords='figure fraction',
xytext=(-20, -20), textcoords='offset points',
ha="right", va="top",
bbox=bbox_args,
arrowprops=arrow_args)
ax1.annotate('axes fraction : 0, 0', xy=(0, 0), xycoords='axes fraction',
xytext=(20, 20), textcoords='offset points',
ha="left", va="bottom",
bbox=bbox_args,
arrowprops=arrow_args)
ax1.annotate('axes fraction : 1, 1', xy=(1, 1), xycoords='axes fraction',
xytext=(-20, -20), textcoords='offset points',
ha="right", va="top",
bbox=bbox_args,
arrowprops=arrow_args)
# It is also possible to generate draggable annotations
an1 = ax1.annotate('Drag me 1', xy=(.5, .7), xycoords='data',
#xytext=(.5, .7), textcoords='data',
ha="center", va="center",
bbox=bbox_args,
#arrowprops=arrow_args
)
an2 = ax1.annotate('Drag me 2', xy=(.5, .5), xycoords=an1,
xytext=(.5, .3), textcoords='axes fraction',
ha="center", va="center",
bbox=bbox_args,
arrowprops=dict(patchB=an1.get_bbox_patch(),
connectionstyle="arc3,rad=0.2",
**arrow_args))
an1.draggable()
an2.draggable()
an3 = ax1.annotate('', xy=(.5, .5), xycoords=an2,
xytext=(.5, .5), textcoords=an1,
ha="center", va="center",
bbox=bbox_args,
arrowprops=dict(patchA=an1.get_bbox_patch(),
patchB=an2.get_bbox_patch(),
connectionstyle="arc3,rad=0.2",
**arrow_args))
# Finally we'll show off some more complex annotation and placement
text = ax2.annotate('xy=(0, 1)\nxycoords=("data", "axes fraction")',
xy=(0, 1), xycoords=("data", 'axes fraction'),
xytext=(0, -20), textcoords='offset points',
ha="center", va="top",
bbox=bbox_args,
arrowprops=arrow_args)
ax2.annotate('xy=(0.5, 0)\nxycoords=artist',
xy=(0.5, 0.), xycoords=text,
xytext=(0, -20), textcoords='offset points',
ha="center", va="top",
bbox=bbox_args,
arrowprops=arrow_args)
ax2.annotate('xy=(0.8, 0.5)\nxycoords=ax1.transData',
xy=(0.8, 0.5), xycoords=ax1.transData,
xytext=(10, 10),
textcoords=OffsetFrom(ax2.bbox, (0, 0), "points"),
ha="left", va="bottom",
bbox=bbox_args,
arrowprops=arrow_args)
ax2.set(xlim=[-2, 2], ylim=[-2, 2])
plt.show()
```
![注释图示例6](https://matplotlib.org/_images/sphx_glr_annotation_demo_006.png)
## 下载这个示例
- [下载python源码: annotation_demo.py](https://matplotlib.org/_downloads/annotation_demo.py)
- [下载Jupyter notebook: annotation_demo.ipynb](https://matplotlib.org/_downloads/annotation_demo.ipynb)

View File

@@ -0,0 +1,316 @@
# 箭头符号演示
新的花式箭头工具的箭头绘制示例。
代码由此人贡献: Rob Knight < rob@spot.colorado.edu >
用法:
![箭头符号图示例](https://matplotlib.org/_images/sphx_glr_arrow_demo_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
rates_to_bases = {'r1': 'AT', 'r2': 'TA', 'r3': 'GA', 'r4': 'AG', 'r5': 'CA',
'r6': 'AC', 'r7': 'GT', 'r8': 'TG', 'r9': 'CT', 'r10': 'TC',
'r11': 'GC', 'r12': 'CG'}
numbered_bases_to_rates = {v: k for k, v in rates_to_bases.items()}
lettered_bases_to_rates = {v: 'r' + v for k, v in rates_to_bases.items()}
def add_dicts(d1, d2):
"""Adds two dicts and returns the result."""
result = d1.copy()
result.update(d2)
return result
def make_arrow_plot(data, size=4, display='length', shape='right',
max_arrow_width=0.03, arrow_sep=0.02, alpha=0.5,
normalize_data=False, ec=None, labelcolor=None,
head_starts_at_zero=True,
rate_labels=lettered_bases_to_rates,
**kwargs):
"""Makes an arrow plot.
Parameters:
data: dict with probabilities for the bases and pair transitions.
size: size of the graph in inches.
display: 'length', 'width', or 'alpha' for arrow property to change.
shape: 'full', 'left', or 'right' for full or half arrows.
max_arrow_width: maximum width of an arrow, data coordinates.
arrow_sep: separation between arrows in a pair, data coordinates.
alpha: maximum opacity of arrows, default 0.8.
**kwargs can be anything allowed by a Arrow object, e.g.
linewidth and edgecolor.
"""
plt.xlim(-0.5, 1.5)
plt.ylim(-0.5, 1.5)
plt.gcf().set_size_inches(size, size)
plt.xticks([])
plt.yticks([])
max_text_size = size * 12
min_text_size = size
label_text_size = size * 2.5
text_params = {'ha': 'center', 'va': 'center', 'family': 'sans-serif',
'fontweight': 'bold'}
r2 = np.sqrt(2)
deltas = {
'AT': (1, 0),
'TA': (-1, 0),
'GA': (0, 1),
'AG': (0, -1),
'CA': (-1 / r2, 1 / r2),
'AC': (1 / r2, -1 / r2),
'GT': (1 / r2, 1 / r2),
'TG': (-1 / r2, -1 / r2),
'CT': (0, 1),
'TC': (0, -1),
'GC': (1, 0),
'CG': (-1, 0)}
colors = {
'AT': 'r',
'TA': 'k',
'GA': 'g',
'AG': 'r',
'CA': 'b',
'AC': 'r',
'GT': 'g',
'TG': 'k',
'CT': 'b',
'TC': 'k',
'GC': 'g',
'CG': 'b'}
label_positions = {
'AT': 'center',
'TA': 'center',
'GA': 'center',
'AG': 'center',
'CA': 'left',
'AC': 'left',
'GT': 'left',
'TG': 'left',
'CT': 'center',
'TC': 'center',
'GC': 'center',
'CG': 'center'}
def do_fontsize(k):
return float(np.clip(max_text_size * np.sqrt(data[k]),
min_text_size, max_text_size))
A = plt.text(0, 1, '$A_3$', color='r', size=do_fontsize('A'),
**text_params)
T = plt.text(1, 1, '$T_3$', color='k', size=do_fontsize('T'),
**text_params)
G = plt.text(0, 0, '$G_3$', color='g', size=do_fontsize('G'),
**text_params)
C = plt.text(1, 0, '$C_3$', color='b', size=do_fontsize('C'),
**text_params)
arrow_h_offset = 0.25 # data coordinates, empirically determined
max_arrow_length = 1 - 2 * arrow_h_offset
max_head_width = 2.5 * max_arrow_width
max_head_length = 2 * max_arrow_width
arrow_params = {'length_includes_head': True, 'shape': shape,
'head_starts_at_zero': head_starts_at_zero}
ax = plt.gca()
sf = 0.6 # max arrow size represents this in data coords
d = (r2 / 2 + arrow_h_offset - 0.5) / r2 # distance for diags
r2v = arrow_sep / r2 # offset for diags
# tuple of x, y for start position
positions = {
'AT': (arrow_h_offset, 1 + arrow_sep),
'TA': (1 - arrow_h_offset, 1 - arrow_sep),
'GA': (-arrow_sep, arrow_h_offset),
'AG': (arrow_sep, 1 - arrow_h_offset),
'CA': (1 - d - r2v, d - r2v),
'AC': (d + r2v, 1 - d + r2v),
'GT': (d - r2v, d + r2v),
'TG': (1 - d + r2v, 1 - d - r2v),
'CT': (1 - arrow_sep, arrow_h_offset),
'TC': (1 + arrow_sep, 1 - arrow_h_offset),
'GC': (arrow_h_offset, arrow_sep),
'CG': (1 - arrow_h_offset, -arrow_sep)}
if normalize_data:
# find maximum value for rates, i.e. where keys are 2 chars long
max_val = 0
for k, v in data.items():
if len(k) == 2:
max_val = max(max_val, v)
# divide rates by max val, multiply by arrow scale factor
for k, v in data.items():
data[k] = v / max_val * sf
def draw_arrow(pair, alpha=alpha, ec=ec, labelcolor=labelcolor):
# set the length of the arrow
if display == 'length':
length = max_head_length + data[pair] / sf * (max_arrow_length -
max_head_length)
else:
length = max_arrow_length
# set the transparency of the arrow
if display == 'alpha':
alpha = min(data[pair] / sf, alpha)
# set the width of the arrow
if display == 'width':
scale = data[pair] / sf
width = max_arrow_width * scale
head_width = max_head_width * scale
head_length = max_head_length * scale
else:
width = max_arrow_width
head_width = max_head_width
head_length = max_head_length
fc = colors[pair]
ec = ec or fc
x_scale, y_scale = deltas[pair]
x_pos, y_pos = positions[pair]
plt.arrow(x_pos, y_pos, x_scale * length, y_scale * length,
fc=fc, ec=ec, alpha=alpha, width=width,
head_width=head_width, head_length=head_length,
**arrow_params)
# figure out coordinates for text
# if drawing relative to base: x and y are same as for arrow
# dx and dy are one arrow width left and up
# need to rotate based on direction of arrow, use x_scale and y_scale
# as sin x and cos x?
sx, cx = y_scale, x_scale
where = label_positions[pair]
if where == 'left':
orig_position = 3 * np.array([[max_arrow_width, max_arrow_width]])
elif where == 'absolute':
orig_position = np.array([[max_arrow_length / 2.0,
3 * max_arrow_width]])
elif where == 'right':
orig_position = np.array([[length - 3 * max_arrow_width,
3 * max_arrow_width]])
elif where == 'center':
orig_position = np.array([[length / 2.0, 3 * max_arrow_width]])
else:
raise ValueError("Got unknown position parameter %s" % where)
M = np.array([[cx, sx], [-sx, cx]])
coords = np.dot(orig_position, M) + [[x_pos, y_pos]]
x, y = np.ravel(coords)
orig_label = rate_labels[pair]
label = r'$%s_{_{\mathrm{%s}}}$' % (orig_label[0], orig_label[1:])
plt.text(x, y, label, size=label_text_size, ha='center', va='center',
color=labelcolor or fc)
for p in sorted(positions):
draw_arrow(p)
# test data
all_on_max = dict([(i, 1) for i in 'TCAG'] +
[(i + j, 0.6) for i in 'TCAG' for j in 'TCAG'])
realistic_data = {
'A': 0.4,
'T': 0.3,
'G': 0.5,
'C': 0.2,
'AT': 0.4,
'AC': 0.3,
'AG': 0.2,
'TA': 0.2,
'TC': 0.3,
'TG': 0.4,
'CT': 0.2,
'CG': 0.3,
'CA': 0.2,
'GA': 0.1,
'GT': 0.4,
'GC': 0.1}
extreme_data = {
'A': 0.75,
'T': 0.10,
'G': 0.10,
'C': 0.05,
'AT': 0.6,
'AC': 0.3,
'AG': 0.1,
'TA': 0.02,
'TC': 0.3,
'TG': 0.01,
'CT': 0.2,
'CG': 0.5,
'CA': 0.2,
'GA': 0.1,
'GT': 0.4,
'GC': 0.2}
sample_data = {
'A': 0.2137,
'T': 0.3541,
'G': 0.1946,
'C': 0.2376,
'AT': 0.0228,
'AC': 0.0684,
'AG': 0.2056,
'TA': 0.0315,
'TC': 0.0629,
'TG': 0.0315,
'CT': 0.1355,
'CG': 0.0401,
'CA': 0.0703,
'GA': 0.1824,
'GT': 0.0387,
'GC': 0.1106}
if __name__ == '__main__':
from sys import argv
d = None
if len(argv) > 1:
if argv[1] == 'full':
d = all_on_max
scaled = False
elif argv[1] == 'extreme':
d = extreme_data
scaled = False
elif argv[1] == 'realistic':
d = realistic_data
scaled = False
elif argv[1] == 'sample':
d = sample_data
scaled = True
if d is None:
d = all_on_max
scaled = False
if len(argv) > 2:
display = argv[2]
else:
display = 'length'
size = 4
plt.figure(figsize=(size, size))
make_arrow_plot(d, display=display, linewidth=0.001, edgecolor=None,
normalize_data=scaled, head_starts_at_zero=True, size=size)
plt.show()
```
## 下载这个示例
- [下载python源码: arrow_demo.py](https://matplotlib.org/_downloads/arrow_demo.py)
- [下载Jupyter notebook: arrow_demo.ipynb](https://matplotlib.org/_downloads/arrow_demo.ipynb)

View File

@@ -0,0 +1,16 @@
# 箭头符号简单演示
![箭头符号简单演示](https://matplotlib.org/_images/sphx_glr_arrow_simple_demo_001.png)
```python
import matplotlib.pyplot as plt
ax = plt.axes()
ax.arrow(0, 0, 0.5, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')
plt.show()
```
## 下载这个示例
- [下载python源码: arrow_simple_demo.py](https://matplotlib.org/_downloads/arrow_simple_demo.py)
- [下载Jupyter notebook: arrow_simple_demo.ipynb](https://matplotlib.org/_downloads/arrow_simple_demo.ipynb)

View File

@@ -0,0 +1,29 @@
# 文本自动换行
Matplotlib can wrap text automatically, but if it's too long, the text will be displayed slightly outside of the boundaries of the axis anyways.
![文本自动换行示例](https://matplotlib.org/_images/sphx_glr_autowrap_001.png)
```python
import matplotlib.pyplot as plt
fig = plt.figure()
plt.axis([0, 10, 0, 10])
t = ("This is a really long string that I'd rather have wrapped so that it "
"doesn't go outside of the figure, but if it's long enough it will go "
"off the top or bottom!")
plt.text(4, 1, t, ha='left', rotation=15, wrap=True)
plt.text(6, 5, t, ha='left', rotation=15, wrap=True)
plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)
plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',
va='top', wrap=True)
plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)
plt.text(-1, 0, t, ha='left', rotation=-15, wrap=True)
plt.show()
```
## 下载这个示例
- [下载python源码: autowrap.py](https://matplotlib.org/_downloads/autowrap.py)
- [下载Jupyter notebook: autowrap.ipynb](https://matplotlib.org/_downloads/autowrap.ipynb)

View File

@@ -0,0 +1,75 @@
# 撰写自定义图例
Composing custom legends piece-by-piece.
**注意**
For more information on creating and customizing legends, see the following pages:
- [Legend guide](https://matplotlib.org/tutorials/intermediate/legend_guide.html)
- [Legend Demo](https://matplotlib.org/tutorials/intermediate/legend_guide.html)
有时您不希望与已绘制的数据明确关联的图例。例如假设您已绘制了10行但不希望每个行都显示图例项。如果您只是绘制线条并调用ax.legend(),您将获得以下内容:
```python
# sphinx_gallery_thumbnail_number = 2
from matplotlib import rcParams, cycler
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
N = 10
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
data = np.array(data).T
cmap = plt.cm.coolwarm
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))
fig, ax = plt.subplots()
lines = ax.plot(data)
ax.legend(lines)
```
![撰写自定义图例](https://matplotlib.org/_images/sphx_glr_custom_legends_001.png)
请注意每行创建一个图例项。在这种情况下我们可以使用未明确绑定到绘制数据的Matplotlib对象组成图例。例如
```python
from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
Line2D([0], [0], color=cmap(.5), lw=4),
Line2D([0], [0], color=cmap(1.), lw=4)]
fig, ax = plt.subplots()
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])
```
![撰写自定义图例2](https://matplotlib.org/_images/sphx_glr_custom_legends_002.png)
还有许多其他Matplotlib对象可以这种方式使用。 在下面的代码中,我们列出了一些常见的代码。
```python
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
legend_elements = [Line2D([0], [0], color='b', lw=4, label='Line'),
Line2D([0], [0], marker='o', color='w', label='Scatter',
markerfacecolor='g', markersize=15),
Patch(facecolor='orange', edgecolor='r',
label='Color Patch')]
# Create the figure
fig, ax = plt.subplots()
ax.legend(handles=legend_elements, loc='center')
plt.show()
```
![撰写自定义图例3](https://matplotlib.org/_images/sphx_glr_custom_legends_003.png)
## 下载这个示例
- [下载python源码: custom_legends.py](https://matplotlib.org/_downloads/custom_legends.py)
- [下载Jupyter notebook: custom_legends.ipynb](https://matplotlib.org/_downloads/custom_legends.ipynb)

View File

@@ -0,0 +1,45 @@
# Dashpoint标签
![Dashpoint标签示例](https://matplotlib.org/_images/sphx_glr_dashpointlabel_001.png)
```python
import matplotlib.pyplot as plt
DATA = ((1, 3),
(2, 4),
(3, 1),
(4, 2))
# dash_style =
# direction, length, (text)rotation, dashrotation, push
# (The parameters are varied to show their effects, not for visual appeal).
dash_style = (
(0, 20, -15, 30, 10),
(1, 30, 0, 15, 10),
(0, 40, 15, 15, 10),
(1, 20, 30, 60, 10))
fig, ax = plt.subplots()
(x, y) = zip(*DATA)
ax.plot(x, y, marker='o')
for i in range(len(DATA)):
(x, y) = DATA[i]
(dd, dl, r, dr, dp) = dash_style[i]
t = ax.text(x, y, str((x, y)), withdash=True,
dashdirection=dd,
dashlength=dl,
rotation=r,
dashrotation=dr,
dashpush=dp,
)
ax.set_xlim((0, 5))
ax.set_ylim((0, 5))
plt.show()
```
## 下载这个示例
- [下载python源码: dashpointlabel.py](https://matplotlib.org/_downloads/dashpointlabel.py)
- [下载Jupyter notebook: dashpointlabel.ipynb](https://matplotlib.org/_downloads/dashpointlabel.ipynb)

View File

@@ -0,0 +1,56 @@
# 日期刻度标签
演示如何使用日期刻度定位器和格式化程序在matplotlib中创建日期图。有关控制主要和次要刻度的更多信息请参阅major_minor_demo1.py
所有matplotlib日期绘图都是通过将日期实例转换为自 0001-01-01 00:00:00 UTC 加上一天后的天数(由于历史原因)来完成的。 转换,刻度定位和格式化是在幕后完成的,因此这对您来说是最透明的。 日期模块提供了几个转换器函数 [matplotlib.dates.date2num](https://matplotlib.org/api/dates_api.html#matplotlib.dates.date2num) 和[matplotlib.dates.num2date](https://matplotlib.org/api/dates_api.html#matplotlib.dates.num2date)。这些可以在[datetime.datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime) 对象和 ``numpy.datetime64`` 对象之间进行转换。
![日期刻度标签示例](https://matplotlib.org/_images/sphx_glr_date_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
# Load a numpy record array from yahoo csv data with fields date, open, close,
# volume, adj_close from the mpl-data/example directory. The record array
# stores the date as an np.datetime64 with a day unit ('D') in the date column.
with cbook.get_sample_data('goog.npz') as datafile:
r = np.load(datafile)['price_data'].view(np.recarray)
fig, ax = plt.subplots()
ax.plot(r.date, r.adj_close)
# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
# round to nearest years...
datemin = np.datetime64(r.date[0], 'Y')
datemax = np.datetime64(r.date[-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)
# format the coords message box
def price(x):
return '$%1.2f' % x
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
plt.show()
```
## 下载这个示例
- [下载python源码: date.py](https://matplotlib.org/_downloads/date.py)
- [下载Jupyter notebook: date.ipynb](https://matplotlib.org/_downloads/date.ipynb)

View File

@@ -0,0 +1,51 @@
# 时间序列的自定义刻度格式化程序
当绘制时间序列(例如,金融时间序列)时,人们经常想要省去没有数据的日子,即周末。下面的示例显示了如何使用“索引格式化程序”来实现所需的绘图。
![时间序列的自定义刻度格式化程序示例](https://matplotlib.org/_images/sphx_glr_date_index_formatter_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
# Load a numpy record array from yahoo csv data with fields date, open, close,
# volume, adj_close from the mpl-data/example directory. The record array
# stores the date as an np.datetime64 with a day unit ('D') in the date column.
with cbook.get_sample_data('goog.npz') as datafile:
r = np.load(datafile)['price_data'].view(np.recarray)
r = r[-30:] # get the last 30 days
# Matplotlib works better with datetime.datetime than np.datetime64, but the
# latter is more portable.
date = r.date.astype('O')
# first we'll do it the default way, with gaps on weekends
fig, axes = plt.subplots(ncols=2, figsize=(8, 4))
ax = axes[0]
ax.plot(date, r.adj_close, 'o-')
ax.set_title("Default")
fig.autofmt_xdate()
# next we'll write a custom formatter
N = len(r)
ind = np.arange(N) # the evenly spaced plot indices
def format_date(x, pos=None):
thisind = np.clip(int(x + 0.5), 0, N - 1)
return date[thisind].strftime('%Y-%m-%d')
ax = axes[1]
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
ax.set_title("Custom tick formatter")
fig.autofmt_xdate()
plt.show()
```
## 下载这个示例
- [下载python源码: date_index_formatter.py](https://matplotlib.org/_downloads/date_index_formatter.py)
- [下载Jupyter notebook: date_index_formatter.ipynb](https://matplotlib.org/_downloads/date_index_formatter.ipynb)

View File

@@ -0,0 +1,103 @@
# 图中插入注释框
![图中插入注释框示例](https://matplotlib.org/_images/sphx_glr_demo_annotation_box_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
AnnotationBbox)
from matplotlib.cbook import get_sample_data
if 1:
fig, ax = plt.subplots()
# Define a 1st position to annotate (display it with a marker)
xy = (0.5, 0.7)
ax.plot(xy[0], xy[1], ".r")
# Annotate the 1st position with a text box ('Test 1')
offsetbox = TextArea("Test 1", minimumdescent=False)
ab = AnnotationBbox(offsetbox, xy,
xybox=(-20, 40),
xycoords='data',
boxcoords="offset points",
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
# Annotate the 1st position with another text box ('Test')
offsetbox = TextArea("Test", minimumdescent=False)
ab = AnnotationBbox(offsetbox, xy,
xybox=(1.02, xy[1]),
xycoords='data',
boxcoords=("axes fraction", "data"),
box_alignment=(0., 0.5),
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
# Define a 2nd position to annotate (don't display with a marker this time)
xy = [0.3, 0.55]
# Annotate the 2nd position with a circle patch
da = DrawingArea(20, 20, 0, 0)
p = Circle((10, 10), 10)
da.add_artist(p)
ab = AnnotationBbox(da, xy,
xybox=(1.02, xy[1]),
xycoords='data',
boxcoords=("axes fraction", "data"),
box_alignment=(0., 0.5),
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
# Annotate the 2nd position with an image (a generated array of pixels)
arr = np.arange(100).reshape((10, 10))
im = OffsetImage(arr, zoom=2)
im.image.axes = ax
ab = AnnotationBbox(im, xy,
xybox=(-50., 50.),
xycoords='data',
boxcoords="offset points",
pad=0.3,
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
# Annotate the 2nd position with another image (a Grace Hopper portrait)
fn = get_sample_data("grace_hopper.png", asfileobj=False)
arr_img = plt.imread(fn, format='png')
imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax
ab = AnnotationBbox(imagebox, xy,
xybox=(120., -80.),
xycoords='data',
boxcoords="offset points",
pad=0.5,
arrowprops=dict(
arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=90,rad=3")
)
ax.add_artist(ab)
# Fix the display limits to see everything
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
```
## 下载这个示例
- [下载python源码: demo_annotation_box.py](https://matplotlib.org/_downloads/demo_annotation_box.py)
- [下载Jupyter notebook: demo_annotation_box.ipynb](https://matplotlib.org/_downloads/demo_annotation_box.ipynb)

View File

@@ -0,0 +1,162 @@
# 文本路径演示
使用文本作为路径。允许这种转换的工具是 [TextPath](https://matplotlib.org/api/textpath_api.html#matplotlib.textpath.TextPath)。可以采用所得的路径,例如,作为图像的剪辑路径。
![文本路径演示](https://matplotlib.org/_images/sphx_glr_demo_text_path_001.png)
```python
import matplotlib.pyplot as plt
from matplotlib.image import BboxImage
import numpy as np
from matplotlib.transforms import IdentityTransform
import matplotlib.patches as mpatches
from matplotlib.offsetbox import AnnotationBbox,\
AnchoredOffsetbox, AuxTransformBox
from matplotlib.cbook import get_sample_data
from matplotlib.text import TextPath
class PathClippedImagePatch(mpatches.PathPatch):
"""
The given image is used to draw the face of the patch. Internally,
it uses BboxImage whose clippath set to the path of the patch.
FIXME : The result is currently dpi dependent.
"""
def __init__(self, path, bbox_image, **kwargs):
mpatches.PathPatch.__init__(self, path, **kwargs)
self._init_bbox_image(bbox_image)
def set_facecolor(self, color):
"""simply ignore facecolor"""
mpatches.PathPatch.set_facecolor(self, "none")
def _init_bbox_image(self, im):
bbox_image = BboxImage(self.get_window_extent,
norm=None,
origin=None,
)
bbox_image.set_transform(IdentityTransform())
bbox_image.set_data(im)
self.bbox_image = bbox_image
def draw(self, renderer=None):
# the clip path must be updated every draw. any solution? -JJ
self.bbox_image.set_clip_path(self._path, self.get_transform())
self.bbox_image.draw(renderer)
mpatches.PathPatch.draw(self, renderer)
if 1:
usetex = plt.rcParams["text.usetex"]
fig = plt.figure(1)
# EXAMPLE 1
ax = plt.subplot(211)
arr = plt.imread(get_sample_data("grace_hopper.png"))
text_path = TextPath((0, 0), "!?", size=150)
p = PathClippedImagePatch(text_path, arr, ec="k",
transform=IdentityTransform())
# p.set_clip_on(False)
# make offset box
offsetbox = AuxTransformBox(IdentityTransform())
offsetbox.add_artist(p)
# make anchored offset box
ao = AnchoredOffsetbox(loc='upper left', child=offsetbox, frameon=True,
borderpad=0.2)
ax.add_artist(ao)
# another text
from matplotlib.patches import PathPatch
if usetex:
r = r"\mbox{textpath supports mathtext \& \TeX}"
else:
r = r"textpath supports mathtext & TeX"
text_path = TextPath((0, 0), r,
size=20, usetex=usetex)
p1 = PathPatch(text_path, ec="w", lw=3, fc="w", alpha=0.9,
transform=IdentityTransform())
p2 = PathPatch(text_path, ec="none", fc="k",
transform=IdentityTransform())
offsetbox2 = AuxTransformBox(IdentityTransform())
offsetbox2.add_artist(p1)
offsetbox2.add_artist(p2)
ab = AnnotationBbox(offsetbox2, (0.95, 0.05),
xycoords='axes fraction',
boxcoords="offset points",
box_alignment=(1., 0.),
frameon=False
)
ax.add_artist(ab)
ax.imshow([[0, 1, 2], [1, 2, 3]], cmap=plt.cm.gist_gray_r,
interpolation="bilinear",
aspect="auto")
# EXAMPLE 2
ax = plt.subplot(212)
arr = np.arange(256).reshape(1, 256)/256.
if usetex:
s = (r"$\displaystyle\left[\sum_{n=1}^\infty"
r"\frac{-e^{i\pi}}{2^n}\right]$!")
else:
s = r"$\left[\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}\right]$!"
text_path = TextPath((0, 0), s, size=40, usetex=usetex)
text_patch = PathClippedImagePatch(text_path, arr, ec="none",
transform=IdentityTransform())
shadow1 = mpatches.Shadow(text_patch, 1, -1,
props=dict(fc="none", ec="0.6", lw=3))
shadow2 = mpatches.Shadow(text_patch, 1, -1,
props=dict(fc="0.3", ec="none"))
# make offset box
offsetbox = AuxTransformBox(IdentityTransform())
offsetbox.add_artist(shadow1)
offsetbox.add_artist(shadow2)
offsetbox.add_artist(text_patch)
# place the anchored offset box using AnnotationBbox
ab = AnnotationBbox(offsetbox, (0.5, 0.5),
xycoords='data',
boxcoords="offset points",
box_alignment=(0.5, 0.5),
)
# text_path.set_size(10)
ax.add_artist(ab)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
```
## 下载这个示例
- [下载python源码: demo_text_path.py](https://matplotlib.org/_downloads/demo_text_path.py)
- [下载Jupyter notebook: demo_text_path.ipynb](https://matplotlib.org/_downloads/demo_text_path.ipynb)

View File

@@ -0,0 +1,57 @@
# 演示文本旋转模式
![演示文本旋转模式示例](https://matplotlib.org/_images/sphx_glr_demo_text_rotation_mode_001.png)
```python
from mpl_toolkits.axes_grid1.axes_grid import ImageGrid
def test_rotation_mode(fig, mode, subplot_location):
ha_list = "left center right".split()
va_list = "top center baseline bottom".split()
grid = ImageGrid(fig, subplot_location,
nrows_ncols=(len(va_list), len(ha_list)),
share_all=True, aspect=True,
# label_mode='1',
cbar_mode=None)
for ha, ax in zip(ha_list, grid.axes_row[-1]):
ax.axis["bottom"].label.set_text(ha)
grid.axes_row[0][1].set_title(mode, size="large")
for va, ax in zip(va_list, grid.axes_column[0]):
ax.axis["left"].label.set_text(va)
i = 0
for va in va_list:
for ha in ha_list:
ax = grid[i]
for axis in ax.axis.values():
axis.toggle(ticks=False, ticklabels=False)
ax.text(0.5, 0.5, "Tpg",
size="large", rotation=40,
bbox=dict(boxstyle="square,pad=0.",
ec="none", fc="0.5", alpha=0.5),
ha=ha, va=va,
rotation_mode=mode)
ax.axvline(0.5)
ax.axhline(0.5)
i += 1
if 1:
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(5.5, 4))
fig.clf()
test_rotation_mode(fig, "default", 121)
test_rotation_mode(fig, "anchor", 122)
plt.show()
```
## 下载这个示例
- [下载python源码: demo_text_rotation_mode.py](https://matplotlib.org/_downloads/demo_text_rotation_mode.py)
- [下载Jupyter notebook: demo_text_rotation_mode.ipynb](https://matplotlib.org/_downloads/demo_text_rotation_mode.ipynb)

View File

@@ -0,0 +1,25 @@
# \dfrac 和 \frac之间的区别
在此示例中,说明了 \dfrac和\frac TeX宏之间的差异; 特别是使用Mathtex时显示样式和文本样式分数之间的差异。
*New in version 2.1*.
**注意**:要将 \dfrac与LaTeX引擎一起使用text.usetexTrue您需要使用text.latex.preamble rc导入amsmath包这是一个不受支持的功能; 因此,在 \frac宏之前使用 \displaystyle选项来获取LaTeX引擎的这种行为可能是个更好的主意。
![dfrac喝frac公式](https://matplotlib.org/_images/sphx_glr_dfrac_demo_001.png)
```python
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(5.25, 0.75))
fig.text(0.5, 0.3, r'\dfrac: $\dfrac{a}{b}$',
horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.7, r'\frac: $\frac{a}{b}$',
horizontalalignment='center', verticalalignment='center')
plt.show()
```
## 下载这个示例
- [下载python源码: dfrac_demo.py](https://matplotlib.org/_downloads/dfrac_demo.py)
- [下载Jupyter notebook: dfrac_demo.ipynb](https://matplotlib.org/_downloads/dfrac_demo.ipynb)

View File

@@ -0,0 +1,49 @@
# 使用工程符号标记刻度线
使用工程格式化程序。
![工程格式化示例](https://matplotlib.org/_images/sphx_glr_engineering_formatter_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import EngFormatter
# Fixing random state for reproducibility
prng = np.random.RandomState(19680801)
# Create artificial data to plot.
# The x data span over several decades to demonstrate several SI prefixes.
xs = np.logspace(1, 9, 100)
ys = (0.8 + 0.4 * prng.uniform(size=100)) * np.log10(xs)**2
# Figure width is doubled (2*6.4) to display nicely 2 subplots side by side.
fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(7, 9.6))
for ax in (ax0, ax1):
ax.set_xscale('log')
# Demo of the default settings, with a user-defined unit label.
ax0.set_title('Full unit ticklabels, w/ default precision & space separator')
formatter0 = EngFormatter(unit='Hz')
ax0.xaxis.set_major_formatter(formatter0)
ax0.plot(xs, ys)
ax0.set_xlabel('Frequency')
# Demo of the options `places` (number of digit after decimal point) and
# `sep` (separator between the number and the prefix/unit).
ax1.set_title('SI-prefix only ticklabels, 1-digit precision & '
'thin space separator')
formatter1 = EngFormatter(places=1, sep="\N{THIN SPACE}") # U+2009
ax1.xaxis.set_major_formatter(formatter1)
ax1.plot(xs, ys)
ax1.set_xlabel('Frequency [Hz]')
plt.tight_layout()
plt.show()
```
## 下载这个示例
- [下载python源码: engineering_formatter.py](https://matplotlib.org/_downloads/engineering_formatter.py)
- [下载Jupyter notebook: engineering_formatter.ipynb](https://matplotlib.org/_downloads/engineering_formatter.ipynb)

View File

@@ -0,0 +1,59 @@
# 花式箭头符号演示
![花式箭头符号演示](https://matplotlib.org/_images/sphx_glr_fancyarrow_demo_001.png)
```python
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
styles = mpatches.ArrowStyle.get_styles()
ncol = 2
nrow = (len(styles) + 1) // ncol
figheight = (nrow + 0.5)
fig1 = plt.figure(1, (4 * ncol / 1.5, figheight / 1.5))
fontsize = 0.2 * 70
ax = fig1.add_axes([0, 0, 1, 1], frameon=False, aspect=1.)
ax.set_xlim(0, 4 * ncol)
ax.set_ylim(0, figheight)
def to_texstring(s):
s = s.replace("<", r"$<$")
s = s.replace(">", r"$>$")
s = s.replace("|", r"$|$")
return s
for i, (stylename, styleclass) in enumerate(sorted(styles.items())):
x = 3.2 + (i // nrow) * 4
y = (figheight - 0.7 - i % nrow) # /figheight
p = mpatches.Circle((x, y), 0.2)
ax.add_patch(p)
ax.annotate(to_texstring(stylename), (x, y),
(x - 1.2, y),
ha="right", va="center",
size=fontsize,
arrowprops=dict(arrowstyle=stylename,
patchB=p,
shrinkA=5,
shrinkB=5,
fc="k", ec="k",
connectionstyle="arc3,rad=-0.05",
),
bbox=dict(boxstyle="square", fc="w"))
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.show()
```
## 下载这个示例
- [下载python源码: fancyarrow_demo.py](https://matplotlib.org/_downloads/fancyarrow_demo.py)
- [下载Jupyter notebook: fancyarrow_demo.ipynb](https://matplotlib.org/_downloads/fancyarrow_demo.ipynb)

View File

@@ -0,0 +1,30 @@
# 花式文本框演示
![花式文本框演示](https://matplotlib.org/_images/sphx_glr_fancytextbox_demo_001.png)
```python
import matplotlib.pyplot as plt
plt.text(0.6, 0.5, "test", size=50, rotation=30.,
ha="center", va="center",
bbox=dict(boxstyle="round",
ec=(1., 0.5, 0.5),
fc=(1., 0.8, 0.8),
)
)
plt.text(0.5, 0.4, "test", size=50, rotation=-30.,
ha="right", va="top",
bbox=dict(boxstyle="square",
ec=(1., 0.5, 0.5),
fc=(1., 0.8, 0.8),
)
)
plt.show()
```
## 下载这个示例
- [下载python源码: fancytextbox_demo.py](https://matplotlib.org/_downloads/fancytextbox_demo.py)
- [下载Jupyter notebook: fancytextbox_demo.ipynb](https://matplotlib.org/_downloads/fancytextbox_demo.ipynb)

View File

@@ -0,0 +1,32 @@
# 图形图例演示
不是在每个轴上绘制图例,而是可以绘制图形的所有子轴上的所有艺术家的图例。
![图形图例演示](https://matplotlib.org/_images/sphx_glr_figlegend_demo_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2)
x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2 * np.pi * x)
y2 = np.exp(-x)
l1, l2 = axs[0].plot(x, y1, 'rs-', x, y2, 'go')
y3 = np.sin(4 * np.pi * x)
y4 = np.exp(-2 * x)
l3, l4 = axs[1].plot(x, y3, 'yd-', x, y4, 'k^')
fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left')
fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right')
plt.tight_layout()
plt.show()
```
## 下载这个示例
- [下载python源码: figlegend_demo.py](https://matplotlib.org/_downloads/figlegend_demo.py)
- [下载Jupyter notebook: figlegend_demo.ipynb](https://matplotlib.org/_downloads/figlegend_demo.ipynb)

View File

@@ -0,0 +1,34 @@
# 配置字体系列
你可以明确地设置为给定字体样式拾取的字体系列(例如serifsans-serifmonSpace)。
在下面的示例中我们只允许一个字体系列Tahoma用于sans-serif字体样式。你是font.family rc param的默认系列例如
```python
rcParams['font.family'] = 'sans-serif'
```
并为font.family设置一个字体样式列表以尝试按顺序查找
```python
rcParams['font.sans-serif'] = ['Tahoma', 'DejaVu Sans',
'Lucida Grande', 'Verdana']
```
```python
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Tahoma']
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], label='test')
ax.legend()
plt.show()
```
## 下载这个示例
- [下载python源码: font_family_rc_sgskip.py](https://matplotlib.org/_downloads/font_family_rc_sgskip.py)
- [下载Jupyter notebook: font_family_rc_sgskip.ipynb](https://matplotlib.org/_downloads/font_family_rc_sgskip.ipynb)

View File

@@ -0,0 +1,40 @@
# 在Matplotlib中使用TTF字体文件
虽然为字体实例显式指向单个ttf文件通常不是一个好主意但您可以使用 ``font_manager.FontProperties`` *fname* 参数执行此操作。
在这里我们使用Matplotlib附带的计算机现代罗马字体``cmr10``)。
有关更灵活的解决方案,请参见[配置字体系列](https://matplotlib.org/gallery/text_labels_and_annotations/font_family_rc_sgskip.html)和[字体演示(面向对象的样式)](https://matplotlib.org/gallery/text_labels_and_annotations/fonts_demo.html)。
```python
import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')
plt.show()
```
![在Matplotlib中使用TTF字体文件](https://matplotlib.org/_images/sphx_glr_font_file_001.png)
## 参考
此示例显示了以下函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.font_manager.FontProperties
matplotlib.axes.Axes.set_title
```
## 下载这个示例
- [下载python源码: font_file.py](https://matplotlib.org/_downloads/font_file.py)
- [下载Jupyter notebook: font_file.ipynb](https://matplotlib.org/_downloads/font_file.ipynb)

View File

@@ -0,0 +1,66 @@
# TTF字体表
Matplotlib支持FreeType字体。下面是一个使用table命令构建字体表的小示例该表按字符代码显示字形。
用法python font_table_ttf.py somefile.ttf
```python
import sys
import os
import matplotlib
from matplotlib.ft2font import FT2Font
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
# the font table grid
labelc = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F']
labelr = ['00', '10', '20', '30', '40', '50', '60', '70', '80', '90',
'A0', 'B0', 'C0', 'D0', 'E0', 'F0']
if len(sys.argv) > 1:
fontname = sys.argv[1]
else:
fontname = os.path.join(matplotlib.get_data_path(),
'fonts', 'ttf', 'DejaVuSans.ttf')
font = FT2Font(fontname)
codes = sorted(font.get_charmap().items())
# a 16,16 array of character strings
chars = [['' for c in range(16)] for r in range(16)]
colors = [[(0.95, 0.95, 0.95) for c in range(16)] for r in range(16)]
plt.figure(figsize=(8, 4), dpi=120)
for ccode, glyphind in codes:
if ccode >= 256:
continue
r, c = divmod(ccode, 16)
s = chr(ccode)
chars[r][c] = s
lightgrn = (0.5, 0.8, 0.5)
plt.title(fontname)
tab = plt.table(cellText=chars,
rowLabels=labelr,
colLabels=labelc,
rowColours=[lightgrn] * 16,
colColours=[lightgrn] * 16,
cellColours=colors,
cellLoc='center',
loc='upper left')
for key, cell in tab.get_celld().items():
row, col = key
if row > 0 and col > 0:
cell.set_text_props(fontproperties=FontProperties(fname=fontname))
plt.axis('off')
plt.show()
```
## 下载这个示例
- [下载python源码: font_table_ttf_sgskip.py](https://matplotlib.org/_downloads/font_table_ttf_sgskip.py)
- [下载Jupyter notebook: font_table_ttf_sgskip.ipynb](https://matplotlib.org/_downloads/font_table_ttf_sgskip.ipynb)

View File

@@ -0,0 +1,121 @@
# 字体演示(面向对象的风格)
使用setter设置字体属性。
请参见字体演示(Kwargs)以使用kwargs实现相同的效果。
![字体演示](https://matplotlib.org/_images/sphx_glr_fonts_demo_001.png)
```python
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
plt.subplot(111, facecolor='w')
font0 = FontProperties()
alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}
# Show family options
families = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
font1 = font0.copy()
font1.set_size('large')
t = plt.text(-0.8, 0.9, 'family', fontproperties=font1,
**alignment)
yp = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
for k, family in enumerate(families):
font = font0.copy()
font.set_family(family)
t = plt.text(-0.8, yp[k], family, fontproperties=font,
**alignment)
# Show style options
styles = ['normal', 'italic', 'oblique']
t = plt.text(-0.4, 0.9, 'style', fontproperties=font1,
**alignment)
for k, style in enumerate(styles):
font = font0.copy()
font.set_family('sans-serif')
font.set_style(style)
t = plt.text(-0.4, yp[k], style, fontproperties=font,
**alignment)
# Show variant options
variants = ['normal', 'small-caps']
t = plt.text(0.0, 0.9, 'variant', fontproperties=font1,
**alignment)
for k, variant in enumerate(variants):
font = font0.copy()
font.set_family('serif')
font.set_variant(variant)
t = plt.text(0.0, yp[k], variant, fontproperties=font,
**alignment)
# Show weight options
weights = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
t = plt.text(0.4, 0.9, 'weight', fontproperties=font1,
**alignment)
for k, weight in enumerate(weights):
font = font0.copy()
font.set_weight(weight)
t = plt.text(0.4, yp[k], weight, fontproperties=font,
**alignment)
# Show size options
sizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
'x-large', 'xx-large']
t = plt.text(0.8, 0.9, 'size', fontproperties=font1,
**alignment)
for k, size in enumerate(sizes):
font = font0.copy()
font.set_size(size)
t = plt.text(0.8, yp[k], size, fontproperties=font,
**alignment)
# Show bold italic
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('x-small')
t = plt.text(-0.4, 0.1, 'bold italic', fontproperties=font,
**alignment)
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('medium')
t = plt.text(-0.4, 0.2, 'bold italic', fontproperties=font,
**alignment)
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('x-large')
t = plt.text(-0.4, 0.3, 'bold italic', fontproperties=font,
**alignment)
plt.axis([-1, 1, 0, 1])
plt.show()
```
## 下载这个示例
- [下载python源码: fonts_demo.py](https://matplotlib.org/_downloads/fonts_demo.py)
- [下载Jupyter notebook: fonts_demo.ipynb](https://matplotlib.org/_downloads/fonts_demo.ipynb)

View File

@@ -0,0 +1,89 @@
# 字体演示kwargs
使用kwargs设置字体属性。
请参阅[字体演示(面向对象样式)](/gallery/text_labels_and_annotations/fonts_demo.html)以使用setter实现相同的效果。
![字体演示](https://matplotlib.org/_images/sphx_glr_fonts_demo_kw_001.png)
```python
import matplotlib.pyplot as plt
plt.subplot(111, facecolor='w')
alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}
# Show family options
families = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
t = plt.text(-0.8, 0.9, 'family', size='large', **alignment)
yp = [0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2]
for k, family in enumerate(families):
t = plt.text(-0.8, yp[k], family, family=family, **alignment)
# Show style options
styles = ['normal', 'italic', 'oblique']
t = plt.text(-0.4, 0.9, 'style', **alignment)
for k, style in enumerate(styles):
t = plt.text(-0.4, yp[k], style, family='sans-serif', style=style,
**alignment)
# Show variant options
variants = ['normal', 'small-caps']
t = plt.text(0.0, 0.9, 'variant', **alignment)
for k, variant in enumerate(variants):
t = plt.text(0.0, yp[k], variant, family='serif', variant=variant,
**alignment)
# Show weight options
weights = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
t = plt.text(0.4, 0.9, 'weight', **alignment)
for k, weight in enumerate(weights):
t = plt.text(0.4, yp[k], weight, weight=weight,
**alignment)
# Show size options
sizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
'x-large', 'xx-large']
t = plt.text(0.8, 0.9, 'size', **alignment)
for k, size in enumerate(sizes):
t = plt.text(0.8, yp[k], size, size=size,
**alignment)
x = -0.4
# Show bold italic
t = plt.text(x, 0.1, 'bold italic', style='italic',
weight='bold', size='x-small',
**alignment)
t = plt.text(x, 0.2, 'bold italic',
style='italic', weight='bold', size='medium',
**alignment)
t = plt.text(x, 0.3, 'bold italic',
style='italic', weight='bold', size='x-large',
**alignment)
plt.axis([-1, 1, 0, 1])
plt.show()
```
## 下载这个示例
- [下载python源码: fonts_demo_kw.py](https://matplotlib.org/_downloads/fonts_demo_kw.py)
- [下载Jupyter notebook: fonts_demo_kw.ipynb](https://matplotlib.org/_downloads/fonts_demo_kw.ipynb)

View File

@@ -0,0 +1,45 @@
# 使用预定义标签的图例
使用图定义图例标签。
```python
import numpy as np
import matplotlib.pyplot as plt
# Make some fake data.
a = b = np.arange(0, 3, .02)
c = np.exp(a)
d = c[::-1]
# Create plots with pre-defined labels.
fig, ax = plt.subplots()
ax.plot(a, c, 'k--', label='Model length')
ax.plot(a, d, 'k:', label='Data length')
ax.plot(a, c + d, 'k', label='Total message length')
legend = ax.legend(loc='upper center', shadow=True, fontsize='x-large')
# Put a nicer background color on the legend.
legend.get_frame().set_facecolor('C0')
plt.show()
```
![预定义标签的示例](https://matplotlib.org/_images/sphx_glr_legend_001.png)
## 参考
此示例显示了以下函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.axes.Axes.plot
matplotlib.pyplot.plot
matplotlib.axes.Axes.legend
matplotlib.pyplot.legend
```
## 下载这个示例
- [下载python源码: legend.py](https://matplotlib.org/_downloads/legend.py)
- [下载Jupyter notebook: legend.ipynb](https://matplotlib.org/_downloads/legend.ipynb)

View File

@@ -0,0 +1,194 @@
# 图例Legend演示
在Matplotlib中绘制图例。
在Matplotlib中有很多方法可以创建和自定义图例。 下面我们将展示一些如何操作的示例。
首先,我们将展示如何为特定线条制作图例。
```python
import matplotlib.pyplot as plt
import matplotlib.collections as mcol
from matplotlib.legend_handler import HandlerLineCollection, HandlerTuple
from matplotlib.lines import Line2D
import numpy as np
t1 = np.arange(0.0, 2.0, 0.1)
t2 = np.arange(0.0, 2.0, 0.01)
fig, ax = plt.subplots()
# note that plot returns a list of lines. The "l1, = plot" usage
# extracts the first element of the list into l1 using tuple
# unpacking. So l1 is a Line2D instance, not a sequence of lines
l1, = ax.plot(t2, np.exp(-t2))
l2, l3 = ax.plot(t2, np.sin(2 * np.pi * t2), '--o', t1, np.log(1 + t1), '.')
l4, = ax.plot(t2, np.exp(-t2) * np.sin(2 * np.pi * t2), 's-.')
ax.legend((l2, l4), ('oscillatory', 'damped'), loc='upper right', shadow=True)
ax.set_xlabel('time')
ax.set_ylabel('volts')
ax.set_title('Damped oscillation')
plt.show()
```
![图例示例](https://matplotlib.org/_images/sphx_glr_legend_demo_001.png)
接下来,我们将演示绘制更复杂的标签。
```python
x = np.linspace(0, 1)
fig, (ax0, ax1) = plt.subplots(2, 1)
# Plot the lines y=x**n for n=1..4.
for n in range(1, 5):
ax0.plot(x, x**n, label="n={0}".format(n))
leg = ax0.legend(loc="upper left", bbox_to_anchor=[0, 1],
ncol=2, shadow=True, title="Legend", fancybox=True)
leg.get_title().set_color("red")
# Demonstrate some more complex labels.
ax1.plot(x, x**2, label="multi\nline")
half_pi = np.linspace(0, np.pi / 2)
ax1.plot(np.sin(half_pi), np.cos(half_pi), label=r"$\frac{1}{2}\pi$")
ax1.plot(x, 2**(x**2), label="$2^{x^2}$")
ax1.legend(shadow=True, fancybox=True)
plt.show()
```
![图例示例2](https://matplotlib.org/_images/sphx_glr_legend_demo_002.png)
在这里,我们将图例附加到更复杂的图上。
```python
fig, axes = plt.subplots(3, 1, constrained_layout=True)
top_ax, middle_ax, bottom_ax = axes
top_ax.bar([0, 1, 2], [0.2, 0.3, 0.1], width=0.4, label="Bar 1",
align="center")
top_ax.bar([0.5, 1.5, 2.5], [0.3, 0.2, 0.2], color="red", width=0.4,
label="Bar 2", align="center")
top_ax.legend()
middle_ax.errorbar([0, 1, 2], [2, 3, 1], xerr=0.4, fmt="s", label="test 1")
middle_ax.errorbar([0, 1, 2], [3, 2, 4], yerr=0.3, fmt="o", label="test 2")
middle_ax.errorbar([0, 1, 2], [1, 1, 3], xerr=0.4, yerr=0.3, fmt="^",
label="test 3")
middle_ax.legend()
bottom_ax.stem([0.3, 1.5, 2.7], [1, 3.6, 2.7], label="stem test")
bottom_ax.legend()
plt.show()
```
![图例示例3](https://matplotlib.org/_images/sphx_glr_legend_demo_003.png)
现在我们将展示带有多个关键图例的图例条目。
```python
fig, (ax1, ax2) = plt.subplots(2, 1, constrained_layout=True)
# First plot: two legend keys for a single entry
p1 = ax1.scatter([1], [5], c='r', marker='s', s=100)
p2 = ax1.scatter([3], [2], c='b', marker='o', s=100)
# `plot` returns a list, but we want the handle - thus the comma on the left
p3, = ax1.plot([1, 5], [4, 4], 'm-d')
# Assign two of the handles to the same legend entry by putting them in a tuple
# and using a generic handler map (which would be used for any additional
# tuples of handles like (p1, p3)).
l = ax1.legend([(p1, p3), p2], ['two keys', 'one key'], scatterpoints=1,
numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)})
# Second plot: plot two bar charts on top of each other and change the padding
# between the legend keys
x_left = [1, 2, 3]
y_pos = [1, 3, 2]
y_neg = [2, 1, 4]
rneg = ax2.bar(x_left, y_neg, width=0.5, color='w', hatch='///', label='-1')
rpos = ax2.bar(x_left, y_pos, width=0.5, color='k', label='+1')
# Treat each legend entry differently by using specific `HandlerTuple`s
l = ax2.legend([(rpos, rneg), (rneg, rpos)], ['pad!=0', 'pad=0'],
handler_map={(rpos, rneg): HandlerTuple(ndivide=None),
(rneg, rpos): HandlerTuple(ndivide=None, pad=0.)})
plt.show()
```
![图例示例4](https://matplotlib.org/_images/sphx_glr_legend_demo_004.png)
最后,还可以编写定义如何对图例进行样式化的自定义对象。
```python
class HandlerDashedLines(HandlerLineCollection):
"""
Custom Handler for LineCollection instances.
"""
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
# figure out how many lines there are
numlines = len(orig_handle.get_segments())
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
leglines = []
# divide the vertical space where the lines will go
# into equal parts based on the number of lines
ydata = ((height) / (numlines + 1)) * np.ones(xdata.shape, float)
# for each line, create the line at the proper location
# and set the dash pattern
for i in range(numlines):
legline = Line2D(xdata, ydata * (numlines - i) - ydescent)
self.update_prop(legline, orig_handle, legend)
# set color, dash pattern, and linewidth to that
# of the lines in linecollection
try:
color = orig_handle.get_colors()[i]
except IndexError:
color = orig_handle.get_colors()[0]
try:
dashes = orig_handle.get_dashes()[i]
except IndexError:
dashes = orig_handle.get_dashes()[0]
try:
lw = orig_handle.get_linewidths()[i]
except IndexError:
lw = orig_handle.get_linewidths()[0]
if dashes[0] is not None:
legline.set_dashes(dashes[1])
legline.set_color(color)
legline.set_transform(trans)
legline.set_linewidth(lw)
leglines.append(legline)
return leglines
x = np.linspace(0, 5, 100)
fig, ax = plt.subplots()
colors = plt.rcParams['axes.prop_cycle'].by_key()['color'][:5]
styles = ['solid', 'dashed', 'dashed', 'dashed', 'solid']
lines = []
for i, color, style in zip(range(5), colors, styles):
ax.plot(x, np.sin(x) - .1 * i, c=color, ls=style)
# make proxy artists
# make list of one line -- doesn't matter what the coordinates are
line = [[(0, 0)]]
# set up the proxy artist
lc = mcol.LineCollection(5 * line, linestyles=styles, colors=colors)
# create the legend
ax.legend([lc], ['multi-line'], handler_map={type(lc): HandlerDashedLines()},
handlelength=2.5, handleheight=3)
plt.show()
```
![图例示例5](https://matplotlib.org/_images/sphx_glr_legend_demo_005.png)
## 下载这个示例
- [下载python源码: legend_demo.py](https://matplotlib.org/_downloads/legend_demo.py)
- [下载Jupyter notebook: legend_demo.ipynb](https://matplotlib.org/_downloads/legend_demo.ipynb)

View File

@@ -0,0 +1,92 @@
# 艺术家中的艺术家
重写基本方法,以便一个艺术家对象可以包含另一个艺术家对象。在这种情况下,该行包含一个文本实例来为其添加标签。
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.transforms as mtransforms
import matplotlib.text as mtext
class MyLine(lines.Line2D):
def __init__(self, *args, **kwargs):
# we'll update the position when the line data is set
self.text = mtext.Text(0, 0, '')
lines.Line2D.__init__(self, *args, **kwargs)
# we can't access the label attr until *after* the line is
# initiated
self.text.set_text(self.get_label())
def set_figure(self, figure):
self.text.set_figure(figure)
lines.Line2D.set_figure(self, figure)
def set_axes(self, axes):
self.text.set_axes(axes)
lines.Line2D.set_axes(self, axes)
def set_transform(self, transform):
# 2 pixel offset
texttrans = transform + mtransforms.Affine2D().translate(2, 2)
self.text.set_transform(texttrans)
lines.Line2D.set_transform(self, transform)
def set_data(self, x, y):
if len(x):
self.text.set_position((x[-1], y[-1]))
lines.Line2D.set_data(self, x, y)
def draw(self, renderer):
# draw my label at the end of the line with 2 pixel offset
lines.Line2D.draw(self, renderer)
self.text.draw(renderer)
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
x, y = np.random.rand(2, 20)
line = MyLine(x, y, mfc='red', ms=12, label='line label')
#line.text.set_text('line label')
line.text.set_color('red')
line.text.set_fontsize(16)
ax.add_line(line)
plt.show()
```
![艺术家中的艺术家](https://matplotlib.org/_images/sphx_glr_line_with_text_001.png)
## 参考
此示例显示了以下函数、方法、类和模块的使用:
```python
import matplotlib
matplotlib.lines
matplotlib.lines.Line2D
matplotlib.lines.Line2D.set_data
matplotlib.artist
matplotlib.artist.Artist
matplotlib.artist.Artist.draw
matplotlib.artist.Artist.set_transform
matplotlib.text
matplotlib.text.Text
matplotlib.text.Text.set_color
matplotlib.text.Text.set_fontsize
matplotlib.text.Text.set_position
matplotlib.axes.Axes.add_line
matplotlib.transforms
matplotlib.transforms.Affine2D
```
## 下载这个示例
- [下载python源码: line_with_text.py](https://matplotlib.org/_downloads/line_with_text.py)
- [下载Jupyter notebook: line_with_text.ipynb](https://matplotlib.org/_downloads/line_with_text.ipynb)

View File

@@ -0,0 +1,46 @@
# 数学文本图像作为numpy数组
从LaTeX字符串制作图像。
```python
import matplotlib.mathtext as mathtext
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc('image', origin='upper')
parser = mathtext.MathTextParser("Bitmap")
parser.to_png('test2.png',
r'$\left[\left\lfloor\frac{5}{\frac{\left(3\right)}{4}} '
r'y\right)\right]$', color='green', fontsize=14, dpi=100)
rgba1, depth1 = parser.to_rgba(
r'IQ: $\sigma_i=15$', color='blue', fontsize=20, dpi=200)
rgba2, depth2 = parser.to_rgba(
r'some other string', color='red', fontsize=20, dpi=200)
fig = plt.figure()
fig.figimage(rgba1, 100, 100)
fig.figimage(rgba2, 100, 300)
plt.show()
```
![数学文本图像作为numpy数组](https://matplotlib.org/_images/sphx_glr_mathtext_asarray_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.mathtext
matplotlib.mathtext.MathTextParser
matplotlib.mathtext.MathTextParser.to_png
matplotlib.mathtext.MathTextParser.to_rgba
matplotlib.figure.Figure.figimage
```
## 下载这个示例
- [下载python源码: mathtext_asarray.py](https://matplotlib.org/_downloads/mathtext_asarray.py)
- [下载Jupyter notebook: mathtext_asarray.ipynb](https://matplotlib.org/_downloads/mathtext_asarray.ipynb)

View File

@@ -0,0 +1,30 @@
# 数学文本演示
使用Matplotlib的内部LaTeX解析器和布局引擎。 有关真正的LaTeX渲染请参阅text.usetex选项。
![数学文本演示](https://matplotlib.org/_images/sphx_glr_mathtext_demo_001.png)
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], 'r', label=r'$\sqrt{x^2}$')
ax.legend()
ax.set_xlabel(r'$\Delta_i^j$', fontsize=20)
ax.set_ylabel(r'$\Delta_{i+1}^j$', fontsize=20)
ax.set_title(r'$\Delta_i^j \hspace{0.4} \mathrm{versus} \hspace{0.4} '
r'\Delta_{i+1}^j$', fontsize=20)
tex = r'$\mathcal{R}\prod_{i=\alpha_{i+1}}^\infty a_i\sin(2 \pi f x_i)$'
ax.text(1, 1.6, tex, fontsize=20, va='bottom')
fig.tight_layout()
plt.show()
```
## 下载这个示例
- [下载python源码: mathtext_demo.py](https://matplotlib.org/_downloads/mathtext_demo.py)
- [下载Jupyter notebook: mathtext_demo.ipynb](https://matplotlib.org/_downloads/mathtext_demo.ipynb)

View File

@@ -0,0 +1,147 @@
# 数学文本例子
Matplotlib的数学渲染引擎的选定功能。
![数学文本例子](https://matplotlib.org/_images/sphx_glr_mathtext_examples_001.png)
Out:
```python
0 $W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$
1 $\alpha_i > \beta_i,\ \alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ \ldots$
2 $\frac{3}{4},\ \binom{3}{4},\ \stackrel{3}{4},\ \left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$
3 $\sqrt{2},\ \sqrt[3]{x},\ \ldots$
4 $\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ \mathrm{or}\ \mathcal{CALLIGRAPHY}$
5 $\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ \hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ \ldots$
6 $\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ \Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ \aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$
7 $\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ \log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ \infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$
```
```python
import matplotlib.pyplot as plt
import subprocess
import sys
import re
# Selection of features following "Writing mathematical expressions" tutorial
mathtext_titles = {
0: "Header demo",
1: "Subscripts and superscripts",
2: "Fractions, binomials and stacked numbers",
3: "Radicals",
4: "Fonts",
5: "Accents",
6: "Greek, Hebrew",
7: "Delimiters, functions and Symbols"}
n_lines = len(mathtext_titles)
# Randomly picked examples
mathext_demos = {
0: r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = "
r"U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} "
r"\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ "
r"U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_"
r"{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$",
1: r"$\alpha_i > \beta_i,\ "
r"\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ "
r"\ldots$",
2: r"$\frac{3}{4},\ \binom{3}{4},\ \stackrel{3}{4},\ "
r"\left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$",
3: r"$\sqrt{2},\ \sqrt[3]{x},\ \ldots$",
4: r"$\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ "
r"\mathrm{or}\ \mathcal{CALLIGRAPHY}$",
5: r"$\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ "
r"\hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ "
r"\ldots$",
6: r"$\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ "
r"\Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ "
r"\aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$",
7: r"$\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ "
r"\log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ "
r"\infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$"}
def doall():
# Colors used in mpl online documentation.
mpl_blue_rvb = (191. / 255., 209. / 256., 212. / 255.)
mpl_orange_rvb = (202. / 255., 121. / 256., 0. / 255.)
mpl_grey_rvb = (51. / 255., 51. / 255., 51. / 255.)
# Creating figure and axis.
plt.figure(figsize=(6, 7))
plt.axes([0.01, 0.01, 0.98, 0.90], facecolor="white", frameon=True)
plt.gca().set_xlim(0., 1.)
plt.gca().set_ylim(0., 1.)
plt.gca().set_title("Matplotlib's math rendering engine",
color=mpl_grey_rvb, fontsize=14, weight='bold')
plt.gca().set_xticklabels("", visible=False)
plt.gca().set_yticklabels("", visible=False)
# Gap between lines in axes coords
line_axesfrac = (1. / (n_lines))
# Plotting header demonstration formula
full_demo = mathext_demos[0]
plt.annotate(full_demo,
xy=(0.5, 1. - 0.59 * line_axesfrac),
xycoords='data', color=mpl_orange_rvb, ha='center',
fontsize=20)
# Plotting features demonstration formulae
for i_line in range(1, n_lines):
baseline = 1 - (i_line) * line_axesfrac
baseline_next = baseline - line_axesfrac
title = mathtext_titles[i_line] + ":"
fill_color = ['white', mpl_blue_rvb][i_line % 2]
plt.fill_between([0., 1.], [baseline, baseline],
[baseline_next, baseline_next],
color=fill_color, alpha=0.5)
plt.annotate(title,
xy=(0.07, baseline - 0.3 * line_axesfrac),
xycoords='data', color=mpl_grey_rvb, weight='bold')
demo = mathext_demos[i_line]
plt.annotate(demo,
xy=(0.05, baseline - 0.75 * line_axesfrac),
xycoords='data', color=mpl_grey_rvb,
fontsize=16)
for i in range(n_lines):
s = mathext_demos[i]
print(i, s)
plt.show()
if '--latex' in sys.argv:
# Run: python mathtext_examples.py --latex
# Need amsmath and amssymb packages.
fd = open("mathtext_examples.ltx", "w")
fd.write("\\documentclass{article}\n")
fd.write("\\usepackage{amsmath, amssymb}\n")
fd.write("\\begin{document}\n")
fd.write("\\begin{enumerate}\n")
for i in range(n_lines):
s = mathext_demos[i]
s = re.sub(r"(?<!\\)\$", "$$", s)
fd.write("\\item %s\n" % s)
fd.write("\\end{enumerate}\n")
fd.write("\\end{document}\n")
fd.close()
subprocess.call(["pdflatex", "mathtext_examples.ltx"])
else:
doall()
```
## 下载这个示例
- [下载python源码: mathtext_examples.py](https://matplotlib.org/_downloads/mathtext_examples.py)
- [下载Jupyter notebook: mathtext_examples.ipynb](https://matplotlib.org/_downloads/mathtext_examples.ipynb)

View File

@@ -0,0 +1,50 @@
# 多线(Multiline)
![多线示例](https://matplotlib.org/_images/sphx_glr_multiline_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
plt.figure(figsize=(7, 4))
ax = plt.subplot(121)
ax.set_aspect(1)
plt.plot(np.arange(10))
plt.xlabel('this is a xlabel\n(with newlines!)')
plt.ylabel('this is vertical\ntest', multialignment='center')
plt.text(2, 7, 'this is\nyet another test',
rotation=45,
horizontalalignment='center',
verticalalignment='top',
multialignment='center')
plt.grid(True)
plt.subplot(122)
plt.text(0.29, 0.4, "Mat\nTTp\n123", size=18,
va="baseline", ha="right", multialignment="left",
bbox=dict(fc="none"))
plt.text(0.34, 0.4, "Mag\nTTT\n123", size=18,
va="baseline", ha="left", multialignment="left",
bbox=dict(fc="none"))
plt.text(0.95, 0.4, "Mag\nTTT$^{A^A}$\n123", size=18,
va="baseline", ha="right", multialignment="left",
bbox=dict(fc="none"))
plt.xticks([0.2, 0.4, 0.6, 0.8, 1.],
["Jan\n2009", "Feb\n2009", "Mar\n2009", "Apr\n2009", "May\n2009"])
plt.axhline(0.4)
plt.title("test line spacing for multiline text")
plt.subplots_adjust(bottom=0.25, top=0.75)
plt.show()
```
## 下载这个示例
- [下载python源码: multiline.py](https://matplotlib.org/_downloads/multiline.py)
- [下载Jupyter notebook: multiline.ipynb](https://matplotlib.org/_downloads/multiline.ipynb)

View File

@@ -0,0 +1,73 @@
# 彩虹文本
该示例演示如何将多个文本对象串在一起。
## 过去
在2012年2月的matplotlib-users列表中GökhanSever提出以下问题
matplotlib中有一种可以部分指定字符串的颜色的方法吗
例子:
```python
plt.ylabel("Today is cloudy.") How can I show "today" as red, "is" as green and "cloudy." as blue?
```
感谢。
Paul Ivanov 的回答:
![彩虹文本](https://matplotlib.org/_images/sphx_glr_rainbow_text_001.png)
```python
import matplotlib.pyplot as plt
from matplotlib import transforms
def rainbow_text(x, y, strings, colors, ax=None, **kw):
"""
Take a list of ``strings`` and ``colors`` and place them next to each
other, with text strings[i] being shown in colors[i].
This example shows how to do both vertical and horizontal text, and will
pass all keyword arguments to plt.text, so you can set the font size,
family, etc.
The text will get added to the ``ax`` axes, if provided, otherwise the
currently active axes will be used.
"""
if ax is None:
ax = plt.gca()
t = ax.transData
canvas = ax.figure.canvas
# horizontal version
for s, c in zip(strings, colors):
text = ax.text(x, y, s + " ", color=c, transform=t, **kw)
text.draw(canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(
text.get_transform(), x=ex.width, units='dots')
# vertical version
for s, c in zip(strings, colors):
text = ax.text(x, y, s + " ", color=c, transform=t,
rotation=90, va='bottom', ha='center', **kw)
text.draw(canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(
text.get_transform(), y=ex.height, units='dots')
rainbow_text(0, 0, "all unicorns poop rainbows ! ! !".split(),
['red', 'cyan', 'brown', 'green', 'blue', 'purple', 'black'],
size=16)
plt.show()
```
## 下载这个示例
- [下载python源码: rainbow_text.py](https://matplotlib.org/_downloads/rainbow_text.py)
- [下载Jupyter notebook: rainbow_text.ipynb](https://matplotlib.org/_downloads/rainbow_text.ipynb)

View File

@@ -0,0 +1,36 @@
# STIX 字体演示
![STIX 字体演示](https://matplotlib.org/_images/sphx_glr_stix_fonts_demo_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
tests = [
r'$\mathcircled{123} \mathrm{\mathcircled{123}}'
r' \mathbf{\mathcircled{123}}$',
r'$\mathsf{Sans \Omega} \mathrm{\mathsf{Sans \Omega}}'
r' \mathbf{\mathsf{Sans \Omega}}$',
r'$\mathtt{Monospace}$',
r'$\mathcal{CALLIGRAPHIC}$',
r'$\mathbb{Blackboard \pi}$',
r'$\mathrm{\mathbb{Blackboard \pi}}$',
r'$\mathbf{\mathbb{Blackboard \pi}}$',
r'$\mathfrak{Fraktur} \mathbf{\mathfrak{Fraktur}}$',
r'$\mathscr{Script}$']
plt.figure(figsize=(8, (len(tests) * 1) + 2))
plt.plot([0, 0], 'r')
plt.axis([0, 3, -len(tests), 0])
plt.yticks(-np.arange(len(tests)))
for i, s in enumerate(tests):
plt.text(0.1, -i, s, fontsize=32)
plt.show()
```
## 下载这个示例
- [下载python源码: stix_fonts_demo.py](https://matplotlib.org/_downloads/stix_fonts_demo.py)
- [下载Jupyter notebook: stix_fonts_demo.ipynb](https://matplotlib.org/_downloads/stix_fonts_demo.ipynb)

View File

@@ -0,0 +1,32 @@
# 使用纹理渲染数学方程
如果设置了rc参数text.usetex则可以使用TeX渲染所有matplotlib文本。这当前在agg和ps后端上工作并且要求你在系统上正确安装了[Text render With LaTeX](https://matplotlib.org/tutorials/text/usetex.html)教程中描述的tex和其他依赖项。第一次运行脚本时你将看到tex和相关工具的大量输出。下一次运行可能是静默的因为许多信息都被缓存。
注意如何使用unicode提供y轴的标签
![使用纹理渲染数学方程示例](https://matplotlib.org/_images/sphx_glr_tex_demo_001.png)
```python
import numpy as np
import matplotlib
matplotlib.rcParams['text.usetex'] = True
import matplotlib.pyplot as plt
t = np.linspace(0.0, 1.0, 100)
s = np.cos(4 * np.pi * t) + 2
fig, ax = plt.subplots(figsize=(6, 4), tight_layout=True)
ax.plot(t, s)
ax.set_xlabel(r'\textbf{time (s)}')
ax.set_ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}', fontsize=16)
ax.set_title(r'\TeX\ is Number $\displaystyle\sum_{n=1}^\infty'
r'\frac{-e^{i\pi}}{2^n}$!', fontsize=16, color='r')
plt.show()
```
## 下载这个示例
- [下载python源码: tex_demo.py](https://matplotlib.org/_downloads/tex_demo.py)
- [下载Jupyter notebook: tex_demo.ipynb](https://matplotlib.org/_downloads/tex_demo.ipynb)

View File

@@ -0,0 +1,84 @@
# 精确文本布局
你可以在数据或轴 (0, 1) 坐标中精确布局文本。此示例显示了文本布局的一些对齐和旋转规范。
![精确文本布局示例](https://matplotlib.org/_images/sphx_glr_text_alignment_001.png)
```python
import matplotlib.pyplot as plt
# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)
ax.text(left, bottom, 'left top',
horizontalalignment='left',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, bottom, 'left bottom',
horizontalalignment='left',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right bottom',
horizontalalignment='right',
verticalalignment='bottom',
transform=ax.transAxes)
ax.text(right, top, 'right top',
horizontalalignment='right',
verticalalignment='top',
transform=ax.transAxes)
ax.text(right, bottom, 'center top',
horizontalalignment='center',
verticalalignment='top',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'right center',
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, 0.5 * (bottom + top), 'left center',
horizontalalignment='left',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
horizontalalignment='center',
verticalalignment='center',
transform=ax.transAxes)
ax.text(right, 0.5 * (bottom + top), 'centered',
horizontalalignment='center',
verticalalignment='center',
rotation='vertical',
transform=ax.transAxes)
ax.text(left, top, 'rotated\nwith newlines',
horizontalalignment='center',
verticalalignment='center',
rotation=45,
transform=ax.transAxes)
plt.axis('off')
plt.show()
```
## 下载这个示例
- [下载python源码: text_alignment.py](https://matplotlib.org/_downloads/text_alignment.py)
- [下载Jupyter notebook: text_alignment.ipynb](https://matplotlib.org/_downloads/text_alignment.ipynb)

View File

@@ -0,0 +1,35 @@
# 使用字典控制文本和标签的样式
此示例显示如何通过创建跨多个函数传递的选项字典来跨多个文本对象和标签共享参数。
![使用字典控制文本和标签的样式示例](https://matplotlib.org/_images/sphx_glr_text_fontdict_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
font = {'family': 'serif',
'color': 'darkred',
'weight': 'normal',
'size': 16,
}
x = np.linspace(0.0, 5.0, 100)
y = np.cos(2*np.pi*x) * np.exp(-x)
plt.plot(x, y, 'k')
plt.title('Damped exponential decay', fontdict=font)
plt.text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', fontdict=font)
plt.xlabel('time (s)', fontdict=font)
plt.ylabel('voltage (mV)', fontdict=font)
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.show()
```
## 下载这个示例
- [下载python源码: text_fontdict.py](https://matplotlib.org/_downloads/text_fontdict.py)
- [下载Jupyter notebook: text_fontdict.ipynb](https://matplotlib.org/_downloads/text_fontdict.ipynb)

View File

@@ -0,0 +1,50 @@
# 默认文本旋转演示
默认情况下Matplotlib执行文本布局的方式与某些人相反因此本示例旨在使其更加清晰。
文本由其边界框(围绕墨水矩形的矩形框)对齐。 操作的顺序是旋转然后对齐。 基本上文本以xy位置为中心围绕此点旋转然后根据旋转文本的边界框对齐。
因此如果指定leftbottom alignment则旋转文本的边界框的左下角将位于文本的xy坐标处。
但是一张图片胜过千言万语!
![默认文本旋转演示](https://matplotlib.org/_images/sphx_glr_text_rotation_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
def addtext(ax, props):
ax.text(0.5, 0.5, 'text 0', props, rotation=0)
ax.text(1.5, 0.5, 'text 45', props, rotation=45)
ax.text(2.5, 0.5, 'text 135', props, rotation=135)
ax.text(3.5, 0.5, 'text 225', props, rotation=225)
ax.text(4.5, 0.5, 'text -45', props, rotation=-45)
for x in range(0, 5):
ax.scatter(x + 0.5, 0.5, color='r', alpha=0.5)
ax.set_yticks([0, .5, 1])
ax.set_xlim(0, 5)
ax.grid(True)
# the text bounding box
bbox = {'fc': '0.8', 'pad': 0}
fig, axs = plt.subplots(2, 1)
addtext(axs[0], {'ha': 'center', 'va': 'center', 'bbox': bbox})
axs[0].set_xticks(np.arange(0, 5.1, 0.5), [])
axs[0].set_ylabel('center / center')
addtext(axs[1], {'ha': 'left', 'va': 'bottom', 'bbox': bbox})
axs[1].set_xticks(np.arange(0, 5.1, 0.5))
axs[1].set_ylabel('left / bottom')
plt.show()
```
## 下载这个示例
- [下载python源码: text_rotation.py](https://matplotlib.org/_downloads/text_rotation.py)
- [下载Jupyter notebook: text_rotation.ipynb](https://matplotlib.org/_downloads/text_rotation.ipynb)

View File

@@ -0,0 +1,38 @@
# 相对线的文本旋转
matplotlib中的文本对象通常相对于屏幕坐标系旋转(即无论轴如何更改沿水平和垂直之间的直线旋转45度打印文本)。但是,有时需要围绕打印上的某个内容旋转文本。在这种情况下,正确的角度将不是该对象在打印坐标系中的角度,而是该对象在屏幕坐标系中显示的角度。此角度是通过将角度从打印转换为屏幕坐标系来找到的,如下面的示例所示。
![相对线的文本旋转示例](https://matplotlib.org/_images/sphx_glr_text_rotation_relative_to_line_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
# Plot diagonal line (45 degrees)
h = plt.plot(np.arange(0, 10), np.arange(0, 10))
# set limits so that it no longer looks on screen to be 45 degrees
plt.xlim([-10, 20])
# Locations to plot text
l1 = np.array((1, 1))
l2 = np.array((5, 5))
# Rotate angle
angle = 45
trans_angle = plt.gca().transData.transform_angles(np.array((45,)),
l2.reshape((1, 2)))[0]
# Plot text
th1 = plt.text(l1[0], l1[1], 'text not rotated correctly', fontsize=16,
rotation=angle, rotation_mode='anchor')
th2 = plt.text(l2[0], l2[1], 'text rotated correctly', fontsize=16,
rotation=trans_angle, rotation_mode='anchor')
plt.show()
```
## 下载这个示例
- [下载python源码: text_rotation_relative_to_line.py](https://matplotlib.org/_downloads/text_rotation_relative_to_line.py)
- [下载Jupyter notebook: text_rotation_relative_to_line.ipynb](https://matplotlib.org/_downloads/text_rotation_relative_to_line.ipynb)

View File

@@ -0,0 +1,22 @@
# 标题组演示
Matplotlib可以显示打印标题居中与一组轴的左侧齐平并与一组轴的右侧齐平。
![设置标题示例](https://matplotlib.org/_images/sphx_glr_titles_demo_001.png)
```python
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.title('Center Title')
plt.title('Left Title', loc='left')
plt.title('Right Title', loc='right')
plt.show()
```
## 下载这个示例
- [下载python源码: titles_demo.py](https://matplotlib.org/_downloads/titles_demo.py)
- [下载Jupyter notebook: titles_demo.ipynb](https://matplotlib.org/_downloads/titles_demo.ipynb)

View File

@@ -0,0 +1,30 @@
# Unicode 负表示
您可以使用正确的排版[Unicode 负号](https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes)或ASCII连字符表示负好有些开发者倾向于这样做。
[rcParams["axes.unicode_minus"]](https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams)控制默认行为。
默认是使用Unicode负号。
![负数示例](https://matplotlib.org/_images/sphx_glr_unicode_minus_001.png)
```python
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
matplotlib.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots()
ax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')
ax.set_title('Using hyphen instead of Unicode minus')
plt.show()
```
## 下载这个示例
- [下载python源码: unicode_minus.py](https://matplotlib.org/_downloads/unicode_minus.py)
- [下载Jupyter notebook: unicode_minus.ipynb](https://matplotlib.org/_downloads/unicode_minus.ipynb)

View File

@@ -0,0 +1,77 @@
# Usetex基线测试
![Usetex基线测试示例](https://matplotlib.org/_images/sphx_glr_usetex_baseline_test_001.png)
```python
import matplotlib.pyplot as plt
import matplotlib.axes as maxes
from matplotlib import rcParams
rcParams['text.usetex'] = True
class Axes(maxes.Axes):
"""
A hackish way to simultaneously draw texts w/ usetex=True and
usetex=False in the same figure. It does not work in the ps backend.
"""
def __init__(self, *args, usetex=False, preview=False, **kwargs):
self.usetex = usetex
self.preview = preview
super().__init__(*args, **kwargs)
def draw(self, renderer):
with plt.rc_context({"text.usetex": self.usetex,
"text.latex.preview": self.preview}):
super().draw(renderer)
subplot = maxes.subplot_class_factory(Axes)
def test_window_extent(ax, usetex, preview):
va = "baseline"
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
text_kw = dict(va=va,
size=50,
bbox=dict(pad=0., ec="k", fc="none"))
test_strings = ["lg", r"$\frac{1}{2}\pi$",
r"$p^{3^A}$", r"$p_{3_2}$"]
ax.axvline(0, color="r")
for i, s in enumerate(test_strings):
ax.axhline(i, color="r")
ax.text(0., 3 - i, s, **text_kw)
ax.set_xlim(-0.1, 1.1)
ax.set_ylim(-.8, 3.9)
ax.set_title("usetex=%s\npreview=%s" % (str(usetex), str(preview)))
fig = plt.figure(figsize=(2 * 3, 6.5))
for i, usetex, preview in [[0, False, False],
[1, True, False],
[2, True, True]]:
ax = subplot(fig, 1, 3, i + 1, usetex=usetex, preview=preview)
fig.add_subplot(ax)
fig.subplots_adjust(top=0.85)
test_window_extent(ax, usetex=usetex, preview=preview)
plt.show()
```
## 下载这个示例
- [下载python源码: usetex_baseline_test.py](https://matplotlib.org/_downloads/usetex_baseline_test.py)
- [下载Jupyter notebook: usetex_baseline_test.ipynb](https://matplotlib.org/_downloads/usetex_baseline_test.ipynb)

View File

@@ -0,0 +1,74 @@
# Usetex 演示
演示如何在绘制中使用latex。
另请参阅 [“使用latex进行文本渲染”](https://matplotlib.org/tutorials/text/usetex.html) 指南。
![Usetex 演示](https://matplotlib.org/_images/sphx_glr_usetex_demo_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
# interface tracking profiles
N = 500
delta = 0.6
X = np.linspace(-1, 1, N)
plt.plot(X, (1 - np.tanh(4 * X / delta)) / 2, # phase field tanh profiles
X, (1.4 + np.tanh(4 * X / delta)) / 4, "C2", # composition profile
X, X < 0, 'k--') # sharp interface
# legend
plt.legend(('phase field', 'level set', 'sharp interface'),
shadow=True, loc=(0.01, 0.48), handlelength=1.5, fontsize=16)
# the arrow
plt.annotate("", xy=(-delta / 2., 0.1), xycoords='data',
xytext=(delta / 2., 0.1), textcoords='data',
arrowprops=dict(arrowstyle="<->", connectionstyle="arc3"))
plt.text(0, 0.1, r'$\delta$',
{'color': 'k', 'fontsize': 24, 'ha': 'center', 'va': 'center',
'bbox': dict(boxstyle="round", fc="w", ec="k", pad=0.2)})
# Use tex in labels
plt.xticks((-1, 0, 1), ('$-1$', r'$\pm 0$', '$+1$'), color='k', size=20)
# Left Y-axis labels, combine math mode and text mode
plt.ylabel(r'\bf{phase field} $\phi$', {'color': 'C0', 'fontsize': 20})
plt.yticks((0, 0.5, 1), (r'\bf{0}', r'\bf{.5}', r'\bf{1}'), color='k', size=20)
# Right Y-axis labels
plt.text(1.02, 0.5, r"\bf{level set} $\phi$", {'color': 'C2', 'fontsize': 20},
horizontalalignment='left',
verticalalignment='center',
rotation=90,
clip_on=False,
transform=plt.gca().transAxes)
# Use multiline environment inside a `text`.
# level set equations
eq1 = r"\begin{eqnarray*}" + \
r"|\nabla\phi| &=& 1,\\" + \
r"\frac{\partial \phi}{\partial t} + U|\nabla \phi| &=& 0 " + \
r"\end{eqnarray*}"
plt.text(1, 0.9, eq1, {'color': 'C2', 'fontsize': 18}, va="top", ha="right")
# phase field equations
eq2 = r'\begin{eqnarray*}' + \
r'\mathcal{F} &=& \int f\left( \phi, c \right) dV, \\ ' + \
r'\frac{ \partial \phi } { \partial t } &=& -M_{ \phi } ' + \
r'\frac{ \delta \mathcal{F} } { \delta \phi }' + \
r'\end{eqnarray*}'
plt.text(0.18, 0.18, eq2, {'color': 'C0', 'fontsize': 16})
plt.text(-1, .30, r'gamma: $\gamma$', {'color': 'r', 'fontsize': 20})
plt.text(-1, .18, r'Omega: $\Omega$', {'color': 'b', 'fontsize': 20})
plt.show()
```
## 下载这个示例
- [下载python源码: usetex_demo.py](https://matplotlib.org/_downloads/usetex_demo.py)
- [下载Jupyter notebook: usetex_demo.ipynb](https://matplotlib.org/_downloads/usetex_demo.ipynb)

View File

@@ -0,0 +1,37 @@
# Usetex 字体效果
此脚本演示了pdf usetex现在支持pdftex.map中指定的字体效果。
![Usetex 字体效果示例](https://matplotlib.org/_images/sphx_glr_usetex_fonteffects_001.png)
```python
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('text', usetex=True)
def setfont(font):
return r'\font\a %s at 14pt\a ' % font
for y, font, text in zip(range(5),
['ptmr8r', 'ptmri8r', 'ptmro8r',
'ptmr8rn', 'ptmrr8re'],
['Nimbus Roman No9 L ' + x for x in
['', 'Italics (real italics for comparison)',
'(slanted)', '(condensed)', '(extended)']]):
plt.text(0, y, setfont(font) + text)
plt.ylim(-1, 5)
plt.xlim(-0.2, 0.6)
plt.setp(plt.gca(), frame_on=False, xticks=(), yticks=())
plt.title('Usetex font effects')
plt.savefig('usetex_fonteffects.pdf')
```
脚本的总运行时间0分1.262秒)
## 下载这个示例
- [下载python源码: usetex_fonteffects.py](https://matplotlib.org/_downloads/usetex_fonteffects.py)
- [下载Jupyter notebook: usetex_fonteffects.ipynb](https://matplotlib.org/_downloads/usetex_fonteffects.ipynb)

View File

@@ -0,0 +1,38 @@
# 文字水印
添加文字水印。
```python
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='orange')
ax.grid()
fig.text(0.95, 0.05, 'Property of MPL',
fontsize=50, color='gray',
ha='right', va='bottom', alpha=0.5)
plt.show()
```
![文字水印示例](https://matplotlib.org/_images/sphx_glr_watermark_text_001.png)
## 参考
此示例中显示了以下函数,方法,类和模块的使用:
```python
import matplotlib
matplotlib.figure.Figure.text
```
## 下载这个示例
- [下载python源码: watermark_text.py](https://matplotlib.org/_downloads/watermark_text.py)
- [下载Jupyter notebook: watermark_text.ipynb](https://matplotlib.org/_downloads/watermark_text.ipynb)