本文介绍了如何重用matplotlib中的图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在4个轴上绘制图,在每个轴上绘制前三个图,最后在最后一个轴上绘制所有3个图.这是代码:
I'd like to make plots on 4 axes, first three individual plot on each axes, and the last all 3 plots on last axes.Here is the code:
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()
生成的图片为:
有没有一种方法可以先定义图,然后将它们添加到轴上,然后再绘制它们?这是我所想到的逻辑:
The resulting picture is:
Is there a way to define plots first and then add them to axes, and then plot them? Here is the logic I had in mind:
#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上绘制line1,在ax2上绘制line2,在ax3上绘制line3,在ax4上绘制line4.
Now plot line1 on ax1, line2 on ax2, line3 on ax3 and line4 on ax4.
推荐答案
这里是一种可能的解决方案.我不确定它是否很漂亮,但是至少它不需要代码重复.
Here is one possible solution. I'm not sure that it's very pretty, but at least it does not require code duplication.
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()
这篇关于如何重用matplotlib中的图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!