Py学习  »  Python

将python plot存储为变量并重新加载它以覆盖另一个plot

Fluid • 6 年前 • 1574 次点击  

在Mathematica中,可以将绘图存储在变量中,然后在以后的某个时间覆盖它们。例如,

plt1 = Plot[Cos[x],{x,0,Pi}];
plt2 = Plot[Sin[x],{x,0,Pi}];
plt3 = Plot[x,{x,0,Pi}];

Show[plt1,plt2]
Show[plt1,plt3]

给出两个图,一个覆盖cos(x)和sin(x)图,另一个覆盖cos(x)和x图。因此,对于第二个覆盖,我不需要回复cos(x),因为它已经保存在plt1中。

我想在python中也会发生同样的事情。我有一个二维函数,绘图很费时,我需要每次都用一些其他的数据来覆盖它。我可以只绘制一次然后将其与其他数据的绘图重叠吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41148
文章 [ 1 ]  |  最新文章 6 年前
ImportanceOfBeingErnest
Reply   •   1 楼
ImportanceOfBeingErnest    7 年前

我将把这个问题解释为关于matplotlib的问题(因为matplotlib被标记了),但是当然还有其他python绘图工具,它们的行为可能不同。

在matplotlib中,一个艺术家(例如一条线)必然是一个图形的一部分。不能将同一艺术家添加到多个图形中。
所以通常的解决办法是不想复制艺术家本身,而是复制艺术家的创作过程。

def mycos(x, ax=None, **kwargs):
    ax = ax or plt.gca()
    ax.plot(x, np.cos(x), **kwargs)

def mysin(x, ax=None, **kwargs):
    ax = ax or plt.gca()
    ax.plot(x, np.sin(x), **kwargs)

x = np.linspace(0,2*np.pi)

# Create one figure with two subplots, plot one function in each subplot
fig, axes = plt.subplots(2)
mycos(x, ax=axes[0])
mysin(x, ax=axes[1])

# Create another figure with one subplot, plot both functions
fig, ax = plt.subplots(1)
mycos(x, ax=ax)
mysin(x, ax=ax)