更改 Matplotlib 中图例的轴

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

我有一个图形,在可变位置有一些插入轴。这些插入轴中的每一个都具有相同的线,因此具有相同的图例。 为了避免使图形混乱,我只想显示这些插图之一的图例,并将其(例如)放置在主轴的右上角,以表明这是一个通用图例。

这是我的代码的简化版本:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import numpy as np


fig, ax = plt.subplots(1, 1)

ax.plot(range(10), range(10))

inset_ax1 = inset_axes(ax,
                       width=1.5,
                       height=1.5,
                       loc='lower right')

inset_ax2 = inset_axes(ax,
                       width=2,                             
                       height=2,                         
                       loc='upper left')

inset_ax1.plot(range(10), np.random.rand(10,3))
inset_ax2.plot(range(10), np.random.rand(10,3))
inset_ax1.legend(['a', 'b', 'c'], loc='upper right')
plt.show()

我尝试使用

ax.add_artist(inset_ax1.legend())
,但这会给出以下警告:
ValueError: Can not reset the axes.  You are probably trying to re-use an artist in more than one Axes which is not supported
。我该如何解决这个问题?

给出一些背景信息:我正在制作一个与此类似的,但我想为所有风玫瑰显示一个图例。插图的位置和数量是可变的。

python matplotlib
1个回答
0
投票

如果您掌握了其中一个插图中的线条,则可以将它们传递给主轴上的图例。请注意,这将覆盖

legend
对主轴上任何艺术家的自动检测。

lines1 = inset_ax1.plot(range(10), np.random.rand(10,3))
lines2 = inset_ax2.plot(range(10), np.random.rand(10,3))

ax.legend(lines1, ['a', 'b', 'c'], loc='upper right')

enter image description here

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