I need to represent multiple datasets on the same canvas and then save each one as a figure. The original canvas is an object that contains a Matplotlib figure with several axis and subplots.
In order not to create this canvas over and over again on each dataset plot, I'd like to recycle it somehow. I mean, keep it in memory and acces to it every time I want.
I have tried this by using copy.copy() function but it doesn't work since all plots end up overlapping each other within the same figure.
Here I add a Minimal Reproducible Code (MRE) to let me understand better. The canvas example figure has been made by modifying Matplotlib's dolphin example.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import copy
class Canvas:
'''Figure example to recycle'''
def __init__(self):
fig, ax = plt.subplots(figsize=(6, 6))
circle = plt.Circle((0.5, 0.5), 1, facecolor='none', edgecolor='black', linewidth=3)
ax.add_patch(circle)
im = plt.imshow(np.random.random((100, 100)), cmap=plt.cm.plasma,
extent=([-0.5,1.5,-0.5,1.5]), alpha=0.6)
im.set_clip_path(circle)
self.fig, self.ax = fig, ax
class Plot:
'''Create a DataFrame and represent its info within a figure'''
def __init__(self):
'''x and y dataframes for xy coordinates'''
self.x = pd.DataFrame(dict(A=np.random.random(50), B=np.random.random(50), C=np.random.random(50),
D=np.random.random(50)), index=np.arange(50))
self.y = pd.DataFrame(dict(A=np.random.random(50), B=np.random.random(50), C=np.random.random(50),
D=np.random.random(50)), index=np.arange(50))
self.Graph = Canvas()
self.fig, self.ax = self.Graph.fig, self.Graph.ax
def draw(self):
'''Plot each column of both dataframes (x and y) into the figure'''
for i,j in zip(self.x.columns, self.y.columns):
copy_Graph = copy.copy(self.Graph)
fig, ax = copy_Graph.fig, copy_Graph.ax
ax.scatter(self.x[i], self.y[j])
ax.axis('off')
fig.savefig('{}.png'.format(i))
A = Plot()
A.draw()
As can be seen in the output figures, different dataset coexist at the same figure (i.e., copy() function did not work), when each dataset should have one figure.
I have also tried copy.deepcopy(), but the next error is constantly raised:
NotImplementedError: TransformNode instances can not be copied. Consider using frozen() instead.
Since the canvas creation for each plot last the 20% of the program execution, I think it's necessary to recycle the Diagram figure. Does anybody know how to achieve this?
Thanks in advance!
