简体   繁体   English

带插图的Matlplotlib图:在原始轴上创建图例

[英]Matlplotlib plot with inset: make legend in original axis

I have a very simple question that I can't find the answer to: 我有一个非常简单的问题,找不到以下答案:

Using matplotlib I plot something in a main plot and then something else in an inset using eg 使用matplotlib我在主图中绘制一些内容,然后在插图中使用例如int绘制其他内容

a = plt.axes([.2, .64, .28, .24])

But after that I want to plot a legend in the main plot again (because the legend contains something found in the meantime). 但是之后,我想在主图中再次绘制图例(因为在此期间图例中包含某些内容)。

How do I do this? 我该怎么做呢? As in how do I go back to the original plot and make the legend? 就像我如何回到原始剧情并制作图例一样?

I tried different things including sca , but nothing has worked. 我尝试了其他方法,包括sca ,但没有任何效果。

plt.sca(main_ax) should have worked. plt.sca(main_ax)应该已经起作用。 Note that if you didn't specify a label for the curve/plot/etc, it won't be shown if you only call plt.legend() . 请注意,如果未为曲线/图/等指定标签,则仅调用plt.legend()不会显示该标签。 (Instead, you'd need to do plt.legend([line], [label]) , or better yet, call plot(x, y, label='some label') .) (相反,您需要执行plt.legend([line], [label]) ,或者更好的是,调用plot(x, y, label='some label') 。)

However, it's better to approach the problem a different way. 但是,最好以其他方式解决问题。

This is one of the many reasons why you'll often see people recommend avoiding the pyplot interface and using Axes/Figure methods instead. 这是您经常看到人们建议避免使用pyplot界面并改用Axes / Figure方法的众多原因之一。 It makes it very clear which axes you're operating on. 它可以很清楚地说明您在哪个轴上进行操作。

For example: 例如:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10), label='Curve 1')

inset = fig.add_axes([.2, .64, .28, .24])
inset.scatter(range(3), range(3))

ax.legend()

plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM