matplotlib 中的图例中的多个标题

Per*_*oob 6 python plot label matplotlib legend

是否可以在 matplotlib 的图例中放置多个“标题”?我想要的是这样的:

Title 1
x label 1
o label2

Title 2
^ label 3
v label 4

...
Run Code Online (Sandbox Code Playgroud)

如果我有 4 条曲线或更多。因为如果我使用 1 个以上的图例,则很难让它们正确对齐,手动设置位置。

Max*_*Noe 7

我最接近的是创建一个空的代理艺术家。我认为问题是它们没有左对齐,但(空)标记的空间仍然存在。

from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 100)

# the comma is to get just the first element of the list returned
plot1, = plt.plot(x, x**2) 
plot2, = plt.plot(x, x**3)

title_proxy = Rectangle((0,0), 0, 0, color='w')

plt.legend([title_proxy, plot1, title_proxy, plot2], 
           ["$\textbf{title1}$", "label1","$\textbf{title2}$", "label2"])
plt.show()
Run Code Online (Sandbox Code Playgroud)


M.O*_*.O. 6

好的,所以我需要这个答案,但当前的答案对我不起作用。就我而言,我事先不知道我“多久”需要图例中的标题。它取决于一些输入变量,因此我需要比手动设置标题位置更灵活的东西。在访问了这里的数十个问题后,我找到了这个非常适合我的解决方案,但也许有更好的方法。

\n
##\xc2\xa0this is what changes sometimes for me depending on how the user decided to input\nparameters=[2, 5]\n\n\n## Titles of each section\ntitle_2 = "\\n$\\\\bf{Title \\, parameter \\, 2}$"\ntitle_4 = "\\n$\\\\bf{Title \\, parameter \\, 4}$"\ntitle_5 = "\\n$\\\\bf{Title \\, parameter \\, 5}$"\n\n\n\ndef reorderLegend(ax=None, order=None):\n    handles, labels = ax.get_legend_handles_labels()\n    info = dict(zip(labels, handles))\n\n    new_handles = [info[l] for l in order]\n    return new_handles, order\n\n\n#########\n### Plots\nfig, ax = plt.subplots(figsize=(10, 10))\nax.set_axis_off()\n\n##\xc2\xa0Order of labels\nall_labels=[]\nif 2 in parameters:\n    ax.add_line(Line2D([], [], color="none", label=title_2)) \n    all_labels.append(title_2)\n    #### Plot your stuff below header 2\n    #### Append corresponding label to all_labels\n\n\n\nif 4 in parameters:\n    ax.add_line(Line2D([], [], color="none", label=title_4))\n    all_labels.append(title_4)\n    #### Plot your stuff below header 4\n    #### Append corresponding label to all_labels\n\nif 5 in parameters:\n    ax.add_line(Line2D([], [], color="none", label=title_5))\n    all_labels.append(title_5)\n    #### Plot your stuff below header 5\n    #### Append corresponding label to all_labels\n\n## Make Legend in correct order\nhandles, labels = reorderLegend(ax=ax, order=all_labels)\nleg = ax.legend(handles=handles, labels=labels, fontsize=12, loc=\'upper left\', bbox_to_anchor=(1.05, 1), ncol=1, fancybox=True, framealpha=1, frameon=False)\n\n##\xc2\xa0Move titles to the left \nfor item, label in zip(leg.legendHandles, leg.texts):\n    if label._text  in [title_2, title_4, title_5]:\n        width=item.get_window_extent(fig.canvas.get_renderer()).width\n        label.set_ha(\'left\')\n        label.set_position((-2*width,0))\n
Run Code Online (Sandbox Code Playgroud)\n

作为示例,我看到以下图例(裁剪掉图像的其余部分)。\n在此输入图像描述

\n