如何在另一个 python 图中添加不同的图(作为插图)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21001088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add different graphs (as an inset) in another python graph
提问by Mac
I'd like to make a graph like that:
我想制作一个这样的图表:


the problem is, I've got the data from some external files, and I can make the background graph, but I have no idea how to add another graph inside of the one that I already have and change the data to have different results in both of them:
问题是,我从一些外部文件中获得了数据,我可以制作背景图,但我不知道如何在我已有的图内添加另一个图并更改数据以获得不同的结果两个都:
Below I am adding the code I am using to do the background graph. Hope someone can help.
下面我添加了我用来做背景图的代码。希望有人能帮忙。
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
plt.rc('text',usetex=True)
font = {'family':'serif','size':16}
plt.rc('font',**font)
plt.rc('legend',**{'fontsize':14})
matplotlib.rcParams['text.latex.preamble']=[r'\usepackage{amsmath}']
data=np.loadtxt(r'C:\...\file.txt')
plt.plot(data[:,0],data[:,6],linewidth = 3,label='B$_0$ = 1.5 T d',linestyle= '--', color='black')
plt.show()
采纳答案by Joe Kington
There's more than one way do to this, depending on the relationship that you want the inset to have.
有不止一种方法可以做到这一点,这取决于您希望插图具有的关系。
If you just want to inset a graph that has no set relationship with the bigger graph, just do something like:
如果您只想插入一个与更大图没有固定关系的图,只需执行以下操作:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
# These are in unitless percentages of the figure size. (0,0 is bottom left)
left, bottom, width, height = [0.25, 0.6, 0.2, 0.2]
ax2 = fig.add_axes([left, bottom, width, height])
ax1.plot(range(10), color='red')
ax2.plot(range(6)[::-1], color='green')
plt.show()


If you want to have some sort of relationship between the two, have a look at some of the examples here: http://matplotlib.org/1.3.1/mpl_toolkits/axes_grid/users/overview.html#insetlocator
如果您想在两者之间建立某种关系,请查看此处的一些示例:http: //matplotlib.org/1.3.1/mpl_toolkits/axes_grid/users/overview.html#insetlocator
This is useful if you want the inset to be a "zoomed in" version, (say, at exactly twice the scale of the original) that will automatically update as you pan/zoom interactively.
如果您希望插图是“放大”版本(例如,恰好是原始比例的两倍),它将在您交互平移/缩放时自动更新,这将非常有用。
For simple insets, though, just create a new axes as I showed in the example above.
但是,对于简单的插图,只需创建一个新轴,如我在上面的示例中所示。
回答by pms
You can do this with inset_axesmethod (see docs):
您可以使用inset_axes方法执行此操作(请参阅文档):
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
inset_axes = inset_axes(parent_axes,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
loc=3)
See this examplefor a full demo.
有关完整演示,请参阅此示例。

