matplotlib - 使用线条/标记创建复杂的自定义图例作为文本中的“浮动”内联
问题描述
问题
我想创建一个复杂的自定义图例,其中行/标记样式以内联方式显示在文本中(如浮点数,例如 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()
解决方案
推荐阅读
- python - 如何知道可以在 Python 3 中为平台设置的最大递归深度?
- xcode - 适用于 Xcode 9.2 的 React Native CLI 版本
- json - 使用 Batch 和 JQ 解析包含多个字符串化 json 的 JSON
- c# - 如何维护 3 个网站之间的语言?
- python - 如何使用正则表达式抓取 json 值
- java - 如何知道我机器上的 jdk 版本?
- java - 同一端口上的多个DatagramSocket,仅首先获得流量
- python - 在 Cython 中使用字符串的 pandas DataFrames(Numpy 数组)
- postgresql - Postgres 删除重复项(多列)以添加唯一约束
- python - Python中的从宽到长