当使用 Matplotlib 画图时,有时不仅需要改变颜色,也需要各种不同的标记。这里详述处理标记的函数,应用于 plot、scatter 和 errorbar 的标记函数。
1.常用标记所有可能的标记如下所示:
| marker | symbol | description |
|---|---|---|
| "." | point | |
| "," | · | pixel |
| "o" | circle | |
| "v" | triangle_down | |
| "^" | triangle_up | |
| "<" | triangle_left | |
| ">" | triangle_right | |
| "1" | tri_down | |
| "2" | tri_up | |
| "3" | tri_left | |
| "4" | tri_right | |
| "8" | octagon | |
| "s" | square | |
| "p" | pentagon | |
| "P" | plus (filled) | |
| "*" | star | |
| "h" | hexagon1 | |
| "H" | hexagon2 | |
| "+" | plus | |
| “x” | x | |
| "X" | x (filled) | |
| "D" | diamond | |
| "d" | thin_diamond | |
| `" | "` | |
| "_" | hline | |
| 0 (TICKLEFT) | tickleft | |
| 1 (TICKRIGHT) | tickright | |
| 2 (TICKUP) | tickup | |
| 3 (TICKDOWN) | tickdown | |
| 4 (CARETLEFT) | caretleft | |
| 5 (CARETRIGHT) | caretright | |
| 6 (CARETUP) | caretup | |
| 7 (CARETDOWN) | caretdown | |
| 8 (CARETLEFTBASE) | caretleft (centered at base) | |
| 9 (CARETRIGHTBASE) | caretright (centered at base) | |
| 10 (CARETUPBASE) | caretup (centered at base) | |
| 11 (CARETDOWNBASE) | caretdown (centered at base) | |
| "None", " " or "" | nothing | |
| '$...$' | 使用 mathtext 渲染字符串。 例如,“$f$”表示显示字母 f 的标记。 | |
| verts | 用于路径顶点的 (x, y) 对列表。 标记的中心位于 (0, 0) 处,并且尺寸被归一化,这样创建的路径就被封装在单元格内。 |
None 是默认值,表示“无”,但是此表是从其他文档中引用的,用于标记输入的有效输入,在这些情况下,None 仍然表示“默认”。
请注意,可以通过 STIX 数学字体定义特殊符号,例如 “$u266B$”。 有关 STIX 字体符号的概述,请参阅 STIX 字体表。 另请参阅 STIX 字体。
从 0 到 11 的整数创建直线和三角形。 这些同样可以通过大写变量访问,例如 CARETDOWNBASE。 因此以下是等价的:
plt.plot([1, 2, 3], marker=11) plt.plot([1, 2, 3], marker=matplotlib.markers.CARETDOWNBASE)2.Marker参考
Matplotlib 支持使用绘图命令的标记参数选择的多个类别的标记。
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
text_style = dict(horizontalalignment='right', verticalalignment='center',
fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
markerfacecolor="tab:blue", markeredgecolor="tab:blue")
def format_axes(ax):
ax.margins(0.2)
ax.set_axis_off()
ax.invert_yaxis()
def split_list(a_list):
i_half = len(a_list) // 2
return a_list[:i_half], a_list[i_half:]
(1) 非填充标记 (Unfilled markers)
非填充的标记是单色的。
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Un-filled markers', fontsize=14)
# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
if func != 'nothing' and m not in Line2D.filled_markers]
for ax, markers in zip(axs, split_list(unfilled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
plt.show()
(2) 填充标记 (Filled markers)
fig, axs = plt.subplots(ncols=2)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
for y, marker in enumerate(markers):
ax.text(-0.5, y, repr(marker), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
plt.show()
(3) 标记填充样式 (Marker fill styles)
填充标记的边缘颜色和填充颜色可以单独指定。 此外,填充样式可以配置为在各个方向上未填充、完全填充或半填充。 半填充样式使用 markerfacecoloralt 作为辅助填充颜色。
fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
color='darkgrey',
markerfacecolor='tab:blue',
markerfacecoloralt='lightsteelblue',
markeredgecolor='brown')
for y, fill_style in enumerate(Line2D.fillStyles):
ax.text(-0.5, y, repr(fill_style), **text_style)
ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
plt.show()
(4) 从 TeX 符号创建的标记 (Markers created from TeX symbols)
使用 MathText,可使用自定义标记符号,例如 “$u266B$”。 有关 STIX 字体符号的概述,请参阅 STIX 字体表。 另请参阅 STIX 字体。
fig, ax = plt.subplots()
fig.suptitle('Mathtext markers', fontsize=14)
fig.subplots_adjust(left=0.4)
marker_style.update(markeredgecolor="none", markersize=15)
markers = ["$1$", r"$frac{1}{2}$", "$f$", "$u266B$", r"$mathcal{A}$"]
for y, marker in enumerate(markers):
# Escape dollars so that the text is written "as is", not as mathtext.
ax.text(-0.5, y, repr(marker).replace("$", r"$"), **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
plt.show()
(5) 从路径创建的标记 (Markers created from Paths)
任何路径都可以用作标记。 下面的示例显示了两条简单的路径星形和圆形,以及更精细的带有切割星形的圆形路径。
import matplotlib.path as mpath
import numpy as np
star = mpath.Path.unit_regular_star(6)
circle = mpath.Path.unit_circle()
# concatenate the circle with an internal cutout of the star
cut_star = mpath.Path(
vertices=np.concatenate([circle.vertices, star.vertices[::-1, ...]]),
codes=np.concatenate([circle.codes, star.codes]))
fig, ax = plt.subplots()
fig.suptitle('Path markers', fontsize=14)
fig.subplots_adjust(left=0.4)
markers = {'star': star, 'circle': circle, 'cut_star': cut_star}
for y, (name, marker) in enumerate(markers.items()):
ax.text(-0.5, y, name, **text_style)
ax.plot([y] * 3, marker=marker, **marker_style)
format_axes(ax)
plt.show()
3.Marker 示例
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.rand(10)
y = np.random.rand(10)
z = np.sqrt(x**2 + y**2)
fig, axs = plt.subplots(2, 3, sharex=True, sharey=True)
# marker symbol
axs[0, 0].scatter(x, y, s=80, c=z, marker=">")
axs[0, 0].set_title("marker='>'")
# marker from TeX
axs[0, 1].scatter(x, y, s=80, c=z, marker=r'$alpha$')
axs[0, 1].set_title(r"marker=r'$alpha$'")
# marker from path
verts = [[-1, -1], [1, -1], [1, 1], [-1, -1]]
axs[0, 2].scatter(x, y, s=80, c=z, marker=verts)
axs[0, 2].set_title("marker=verts")
# regular polygon marker
axs[1, 0].scatter(x, y, s=80, c=z, marker=(5, 0))
axs[1, 0].set_title("marker=(5, 0)")
# regular star marker
axs[1, 1].scatter(x, y, s=80, c=z, marker=(5, 1))
axs[1, 1].set_title("marker=(5, 1)")
# regular asterisk marker
axs[1, 2].scatter(x, y, s=80, c=z, marker=(5, 2))
axs[1, 2].set_title("marker=(5, 2)")
plt.tight_layout()
plt.show()
结果图形如下:
参考资源[1] matplotlib.markers
[2] Marker reference
[3] Marker examples



