如何在matplotlib中重用绘图?

2024-04-27 16:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在四个轴上画出图,每个轴上的前三个单独的图,最后三个都在最后一个轴上。 代码如下:

from numpy import *
from matplotlib.pyplot import *
fig=figure()
data=arange(0,10,0.01)
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4)

line1=ax1.plot(data,data)
line2=ax2.plot(data, data**2/10, ls='--', color='green')
line3=ax3.plot(data, np.sin(data), color='red')
#could I somehow use previous plots, instead recreating them all?
line4=ax4.plot(data,data)
line4=ax4.plot(data, data**2/10, ls='--', color='green')
line4=ax4.plot(data, np.sin(data), color='red')
show()

结果图片是:
enter image description here
有没有办法先定义绘图,然后将其添加到轴上,然后再绘图?以下是我的逻辑:

#this is just an example, implementation can be different
line1=plot(data, data)
line2=plot(data, data**2/10, ls='--', color='green')
line3=plot(data, np.sin(data), color='red')
line4=[line1, line2, line3]

现在打印ax1上的第1行、ax2上的第2行、ax3上的第3行和ax4上的第4行。


Tags: adddataplotfiggreenlscolorline1
3条回答

这里有一个可能的解决方案。我不确定它是否漂亮,但至少它不需要代码复制。

import numpy as np, copy
import matplotlib.pyplot as plt, matplotlib.lines as ml

fig=plt.figure(1)
data=np.arange(0,10,0.01)
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4)

#create the lines
line1=ml.Line2D(data,data)
line2=ml.Line2D(data,data**2/10,ls='--',color='green')
line3=ml.Line2D(data,np.sin(data),color='red')
#add the copies of the lines to the first 3 panels
ax1.add_line(copy.copy(line1))
ax2.add_line(copy.copy(line2))
ax3.add_line(copy.copy(line3))

[ax4.add_line(_l) for _l in [line1,line2,line3]] # add 3 lines to the 4th panel

[_a.autoscale() for _a in [ax1,ax2,ax3,ax4]] # autoscale if needed
plt.draw()

我认为您的用法很好,但是您可以像这样将所有数据对传递给x,y(尽管这会使阅读变得非常糟糕!)以下内容:

ax4.plot(data, data, data, data**2 / 10, data, np.sin(data))

另一种有趣的方式是这样的:

graph_data = [(data, data), (data, data**2 / 10), (data, np.sin(data))]
[ax4.plot(i,j) for i,j in graph_data]

我在jupyter笔记本中有一个更简单的用例。假设您已经在某个地方存储了一个figure对象,那么您如何才能对其进行复制。 例如:

单元格1:

f = plt.figure(figsize=(18, 6))
f.suptitle("Hierarchical Clustring", fontsize=20)
dendrogram(Z, color_threshold=cut_off,
           truncate_mode='lastp',
           p=20)

单元格2:

#plot f again, the answer is really simple
f
plt.show()

就这样。这样做的好处是可以将图形存储在对象中,然后在必要时使用它们。

相关问题 更多 >