Can You Copy Only Some Subplots To A New Figure?
Is there a way to copy an axis (subplot) to a new figure? This is straightforward in other languages, but I understand that not even a deep copy would work with python's matplotlib
Solution 1:
This is really @Ernest's answer; he pointed me in the right direction. I am typing this here as an answer for future reference, in the hope it can be useful to others. Basically I had to use change_geometry after deleting the subplots I didn't need. I think ggplot in the R universe has a cleaner implementation, but, overall, this seems OK - not too cumbersome. I have commented the code below - hope it's clear enough:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import io
sns.set(style='darkgrid')
#create the subplots
n=int(100)
x=np.arange(0,n)
fig, ax = plt.subplots(3,2)
for i,a in enumerate(ax.flatten() ):
y= np.random.rand(n)
sns.lineplot( x, y , ax =a )
a.set_title('Chart # ' + str(i+1))
a.set_xlabel('my x')
a.set_ylabel('my y')
# pickle the figure, then unpickle it to a new figure
buf = io.BytesIO()
pickle.dump(fig, buf)
buf.seek(0)
fig2=pickle.load(buf)
# sets which subplots to keep
# note that i == 1correponds to a[0,1]
tokeep=[1,2]
axestokeep=[]
for i,a in enumerate(fig2.axes):
if not i in(tokeep):
fig2.delaxes(a)
else:
axestokeep.extend([a])
axestokeep[0].change_geometry(1,2,1)
axestokeep[1].change_geometry(1,2,2)
Post a Comment for "Can You Copy Only Some Subplots To A New Figure?"