首页 > 解决方案 > 独立处理图例标记

问题描述

我有两种线的情节:实线和虚线。实线和虚线都代表不同条件下的相同数量,并且它们具有相同的颜色。

现在,我想添加一个ax.text()实线的标记来表示实线表示该条件下的数量,另一个ax.text()带有虚线的标记表示另一个条件。不知何故,我的意思是这样的:

ax.text(0.9, 0.5, solid_marker + 'condition 1')
ax.text(0.9, 0.4, dashed_marker + 'condition 2')

好吧,就像这张照片中的东西:

我想做的例子:

在此处输入图像描述

有人知道怎么做吗?是否可以在图中的随机文本中使用标记的符号?

谢谢!

标签: pythonmatplotlibtextlegend

解决方案


您的图例规格不是标准的。您需要手动创建它。这是一个可运行的代码,可以产生你需要的东西。

#import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

# Need to create legends manually

# First legend
#red_patch = mpatches.Patch(color='red', label='The red data')
black_line = mlines.Line2D([], [], color='black', linewidth=1.5, label=r'$Z_n$')
green_line = mlines.Line2D([], [], color='green', linewidth=1.5, label=r'$Z_p$')
red_line = mlines.Line2D([], [], color='red', linewidth=1.5, label=r'$Z_\pi$')

# Second legend
line_solid = mlines.Line2D([], [], color='black', linestyle='-', linewidth=1.5, label=r'$n_\beta = n_o$')
line_dashed = mlines.Line2D([], [], color='black', linestyle='--', linewidth=1.5, label=r'$n_\beta = n_o/2$')

first_legend = plt.legend(handles=[black_line, green_line, red_line], loc=1)
ax = plt.gca().add_artist(first_legend)
second_legend = plt.legend(handles=[line_solid, line_dashed], loc='best', \
                           bbox_to_anchor=(0.5, 0.20, 0.5, 0.5)) #best upper-right
second_legend.set_frame_on(False)

plt.show()

输出图:

传奇01


推荐阅读