如何在图例中添加不带标记的标签并代替它们(左对齐合并标签和标记)

问题描述 投票:0回答:1

我想将一些参数及其值添加到图例中,这些图例没有标记,并且必须左对齐放置在其他标记位置的顶部(即在具有其他标记的列中)。如果我们只有一个柱状图例,则可以通过在图例中对它们进行标题来完成。当在图例中指定两列或更多列时,如果使用 title 方法,第二列中的第一项将不会与标题放在一行中,而是与标题中的第一个标签放在一行中,就会出现问题。第一栏。有什么办法可以自动治愈吗?怎么办?

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D


plt.plot([], [], linestyle='--', color='black', label='Dashed Line')
plt.plot([], [], linestyle=':', color='black', label='Dotted Line')
plt.plot([], [], linestyle='-', linewidth=2, color='black', label='Double Solid Line')
plt.plot([], [], linestyle='-.', color='black', label='Dash-Dot Line')

legend_ETP = Line2D([0], [0], marker='o', c='k', ls='None', markerfacecolor='k', markersize=8, label="Far")
legend_IOTP = Line2D([0], [0], marker='s', c='k', ls='None', markerfacecolor='k', markersize=8, label="Near")
legend_void = Line2D([0], [0], marker='', ls='None', label="")

ELS_handles, ELS_labels = plt.gca().get_legend_handles_labels()

Dw_leg = 'Exact = 0.5'

new_handles = [legend_ETP] + [legend_IOTP] + ELS_handles
new_labels = ["Far"] + ["Near"] + ELS_labels
legend = plt.legend(handles=new_handles, labels=new_labels, fontsize=12, loc='lower left', ncol=2, title=Dw_leg)
legend._legend_box.align = "left"

# new_handles = [legend_void] + [legend_ETP] + [legend_IOTP] + ELS_handles
# new_labels = [Dw_leg] + ["Far"] + ["Near"] + ELS_labels
# legend = plt.legend(handles=new_handles, labels=new_labels, fontsize=12, loc='lower left', ncol=2)

plt.show()

python matplotlib
1个回答
0
投票

您应该执行以下操作:

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

x = [1, 2, 3, 4]
y = [10, 20, 30, 40]

plt.plot(x, [i * 1.1 for i in y], linestyle='--', color='black', label='Dashed Line')
plt.plot(x, [i * 0.9 for i in y], linestyle=':', color='black', label='Dotted Line')
plt.plot(x, [i * 1.2 for i in y], linestyle='-', linewidth=2, color='black', label='Double Solid Line')
plt.plot(x, [i * 0.8 for i in y], linestyle='-.', color='black', label='Dash-Dot Line')

legend_ETP = Line2D([0], [0], marker='o', color='k', linestyle='None', markerfacecolor='k', markersize=8, label="Far")
legend_IOTP = Line2D([0], [0], marker='s', color='k', linestyle='None', markerfacecolor='k', markersize=8, label="Near")
legend_void = Line2D([0], [0], marker='', linestyle='None', label="")

param_title = Line2D([0], [0], marker='', linestyle='None', label="Exact = 0.5")

handles, labels = plt.gca().get_legend_handles_labels()

new_handles = [param_title, legend_void, legend_ETP, legend_IOTP] + handles
new_labels = ["Exact = 0.5", ""] + ["Far", "Near"] + labels

legend = plt.legend(new_handles, new_labels, fontsize=12, loc='lower left', ncol=2, title="Legend")
legend._legend_box.align = "left"

plt.show()

这给出了

© www.soinside.com 2019 - 2024. All rights reserved.