Hub*_*chr 4 python plot matplotlib
我有2个或更多图例的剧情。如何“获得”所有图例以更改(例如)图例中的颜色和线条样式?
handles, labels = ax.get_legend_handles_labels()
只给了我“第一个”图例,我将其添加到绘图中plt.legend()
。但是我也想要其他传说,我将其添加到plt.gca().add_artist(leg2)
我该怎么做?
替代:ax.get_legend()
legends = ax.get_legends()
Run Code Online (Sandbox Code Playgroud)
要访问图例的属性:
legends = ax.get_legend()
dict_legends = {'Legends': dict()}
if not isinstance(legends, list):
legends = [legends]
for i, legend in enumerate(legends):
dict_legend = dict()
for j, obj in enumerate(lgnd.get_texts()):
dict_obj = dict()
dict_fp = dict()
text = obj.get_text()
position = obj.get_position()
color = obj.get_color()
dict_obj.update({'Text': text,
'Position': tuple(position),
'Color': color})
obj_fp = obj.get_font_properties()
dict_fp.update({'Font_Name': obj_fp.get_name()})
fontconfig_pattern = obj_fp.get_fontconfig_pattern()
font_properties = str.split(fontconfig_pattern,":")
for fp in font_properties:
if not (fp.strip()==''):
key, value = fp.split("=")
dict_fp.update({str.title(key): value})
dict_fp.update({'fontconfig_pattern': fontconfig_pattern})
dict_obj.update({'Font_Properties': dict_fp})
dict_legend.update({'Text_Object_{}'.format(j+1): dict_obj})
dict_legends['Legends'].update({'Legend_{}'.format(i): {'Legend_Object': legend,
'Contents': dict_legend}})
print(dict_legends)
Run Code Online (Sandbox Code Playgroud)
# Windows: 10
# Python: 3.6
# Matplotlib: 2.2.2
Run Code Online (Sandbox Code Playgroud)
您可以从轴上获取所有子项,并使用以下命令对图例类型进行过滤:
legends = [c for c in ax.get_children() if isinstance(c, mpl.legend.Legend)]
Run Code Online (Sandbox Code Playgroud)
但这完全有用吗?如果我像您提到的那样添加更多图例,我会看到多个Legend
孩子,但所有孩子都指向同一个对象。
编辑:
轴本身保留添加的最后一个图例,因此,如果使用来添加前一个图例.add_artist()
,则会看到多个不同的图例:
例如:
fig, ax = plt.subplots()
l1, = ax.plot(x,y, 'k', label='l1')
leg1 = plt.legend([l1],['l1'])
l2, = ax.plot(x,y, 'k', label='l2')
leg2 = plt.legend([l2],['l2'])
ax.add_artist(leg1)
print(ax.get_children())
Run Code Online (Sandbox Code Playgroud)
返回这些对象:
[<matplotlib.axis.XAxis at 0xd0e6eb8>,
<matplotlib.axis.YAxis at 0xd0ff7b8>,
<matplotlib.lines.Line2D at 0xd0f73c8>,
<matplotlib.lines.Line2D at 0xd5c1a58>,
<matplotlib.legend.Legend at 0xd5c1860>,
<matplotlib.legend.Legend at 0xd5c4b70>,
<matplotlib.text.Text at 0xd5b1dd8>,
<matplotlib.text.Text at 0xd5b1e10>,
<matplotlib.text.Text at 0xd5b1e48>,
<matplotlib.patches.Rectangle at 0xd5b1e80>,
<matplotlib.spines.Spine at 0xd0e6da0>,
<matplotlib.spines.Spine at 0xd0e6ba8>,
<matplotlib.spines.Spine at 0xd0e6208>,
<matplotlib.spines.Spine at 0xd0f10f0>]
Run Code Online (Sandbox Code Playgroud)
是否要执行此操作还有待观察!?您也可以自己独立于轴存储线(或其他类型)。