Python 向现有图形添加新图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39101203/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:52:39  来源:igfitidea点击:

add new plot to existing figure

pythonmatplotlibplot

提问by Jan-Bert

I have a script with some plots ( see example code). After some other things i want to add a new plot to an existing one. But when i try that it add the plot by the last created figure(now fig2). I can't figure out how to change that...

我有一个带有一些情节的脚本(参见示例代码)。在其他一些事情之后,我想为现有的情节添加一个新的情节。但是当我尝试通过最后创建的图形(现在是 fig2)添加绘图时。我不知道如何改变它......

import matplotlib.pylab as plt
import numpy as np

n = 10
x1 = np.arange(n)
y1 = np.arange(n)    

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x1,y1)
fig1.show()

x2 = np.arange(10)
y2 = n/x2

# add new data and create new figure
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(x2,y2)
fig2.show()

# do something with data to compare with new data
y1_geq = y1 >= y2
y1_a = y1**2
ax1.plot(y1_geq.nonzero()[0],y1[y1_geq],'ro')
fig1.canvas.draw

回答by albert

Since your code is not runnable without errors I'll provide a sample snippet showing how to plot several data in same graph/diagram:

由于您的代码无法在没有错误的情况下运行,我将提供一个示例片段,展示如何在同一图形/图表中绘制多个数据:

import matplotlib.pyplot as plt

xvals = [i for i in range(0, 10)]
yvals1 = [i**2 for i in range(0, 10)]
yvals2 = [i**3 for i in range(0, 10)]

f, ax = plt.subplots(1)
ax.plot(xvals, yvals1)
ax.plot(xvals, yvals2)

So the basic idea is to call ax.plot()for all datasets you need to plot into the same plot.

因此,基本思想是将ax.plot()您需要绘制的所有数据集调用到同一个图中。