首页 > 解决方案 > 使用线条/标记创建复杂的自定义图例作为文本中的“浮动”内联

问题描述

问题

我想创建一个复杂的自定义图例,其中行/标记样式以内联方式显示在文本中(如浮点数,例如 LaTeX 中的内联方程)。但是,我不知道如何优雅地做到这一点。

期望的输出

在此处输入图像描述

所需代码

我的典型行的理想代码如下所示:

h2 = ax.plot(..., marker='o', color='tab:green')
h4 = ax.plot(..., marker='o', color='tab:blue')
h8 = ax.plot(..., marker='o', color='tab:purple')
h16 = ax.plot(..., marker='o', color='tab:red')

ax.text(0, 1, ' '.join([
    'depth', 
    create_float(h2), '(2)', 
    create_float(h4), '(4)', 
    create_float(h8), '(8)', 
    create_float(h16), '(16)'])

当前代码

我目前令人失望的代码是:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.text(0, -1, 'width: 2', ha='left', va='center')

x = 0
ax.text(x, 0, 'depth:', ha='left', va='center')
x += 0.2
ax.plot(x, 0, marker='o', color='tab:green')
x += 0.08
ax.text(x, 0, '(2)', ha='center', va='center')
x += 0.08
ax.plot(x, 0, marker='o', color='tab:blue')
x += 0.08
ax.text(x, 0, '(4)', ha='center', va='center')
x += 0.08
ax.plot(x, 0, marker='o', color='tab:purple')
x += 0.08
ax.text(x, 0, '(8)', ha='center', va='center')
x += 0.08
ax.plot(x, 0, marker='o', color='tab:red')
x += 0.08
ax.text(x, 0, '(16)', ha='center', va='center')

x = 0
ax.text(x, 1, 'shuffle:', ha='left', va='center')
x += 0.2
ax.plot(x, 1, marker='s', color='k')
x += 0.1
ax.text(x, 1, "(yes)", ha='center', va='center')
x += 0.1
ax.plot(x, 1, marker='o', color='k')
x += 0.1
ax.text(x, 1, "(no)", ha='center', va='center')

x = 0
ax.text(x, 2, r'probability:', ha='left', va='center')
x += 0.31
ax.plot(x, 2, marker='o', color='k', fillstyle='full')
x += 0.16
ax.text(x, 2, "(random)", ha='center', va='center')
x += 0.16
ax.plot(x, 2, marker='o', color='k', fillstyle='none')
x += 0.16
ax.text(x, 2, "(constant)", ha='center', va='center')

ax.set_xlim([-0.2, 1.5])
ax.set_ylim([-2.2, 4.2])

plt.savefig('plot.png')
plt.close()

标签: matplotlib

解决方案


推荐阅读