我想自定义一个Matplotlib图例,以便其中一个标签由两个不同样式的标记表示(例如☆/▽我的标签)。我已经看到您可以通过为标记制作补丁来自定义图例标记,但是您可以创建并使用两个补丁(并且在推送时可能添加“/”作为分隔符)吗?还可以选择使用 TikZ 为标记创建 LaTeX 字符串,但这似乎有点过头了。
一种方法是使用 mathtext 定义自定义标记(请参阅matplotlib 文档)并使用代理定义子类的图例句柄:
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
# Generate some data :
x1 = np.arange(1, 20)
y1 = np.log(x1) + np.random.uniform(-1, 1, size=len(x1))/5
x2 = np.arange(1, 20)
y2 = np.log(x2) + np.random.uniform(-1, 1, size=len(x2))/5
# Plot data :
fig, ax = plt.subplots()
h1, = ax.plot(x1[x1>5], y1[x1>5], ls='none', marker=r'$\star$',
ms=12, mec='0.15', mfc='0.15', mew=1, alpha=0.5)
h2, = ax.plot(x2[x2>5], y2[x2>5], ls='none', marker=r'$\blacktriangledown$',
ms=12, mec='0.15', mfc='0.15', mew=1, alpha=0.5)
ax.plot(x1[x1<=5], y1[x1<=5], ls='none', marker=r'$\star$',
ms=12, mec='red', mfc='red', mew=1, alpha=0.5)
ax.plot(x2[x2<=5], y2[x2<=5], ls='none', marker=r'$\blacktriangledown$',
ms=12, mec='red', mfc='red', mew=1, alpha=0.5)
# Create a proxy for the subclass :
h3, = ax.plot([], ls='none', marker=r'$\star/\blacktriangledown$',
ms=24, mec='red', mfc='red', mew=1, alpha=0.5)
# Generate legend :
handles = [h1, h2, h3]
labels = ['dataset1', 'dataset2', 'transient state']
ax.legend(handles, labels, loc=4, ncol=1, numpoints=1, frameon=False)
# Save and show the figure :
fig.savefig('custom_legend_markers.png')
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1180 次 |
| 最近记录: |