I have a matplotlib plot that I had created earlier and had saved it as an image (let's call it fig-1 ). Now, I have a script which generates another plot and I want that plot to be overlayed on the previous image ( fig-1 ).
Due to environment problems, both the plots can't be generated by a single script.
How should I proceed?
The first plot I am generating is in python3 and the second script I have to run is in python2 . The two environments cannot be changed since one is running in ros2 and the second is running in ros1.
On pickling the first plot in python3 and then trying to unpickle it in python2 , I am encountering the following error:
Traceback (most recent call last):
File "./latencycheckclient.py", line 58, in <module>
fig_handle = pl.load(file('/home/arusarka/dev_ws/src/devel_space/devel_space/ros2_latency.pickle','rb'))
File "/usr/lib/python2.7/pickle.py", line 1384, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 864, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 1223, in load_build
setstate(state)
File "/usr/lib/python2.7/dist-packages/matplotlib/transforms.py", line 1684, in __setstate__
self._init(state['child'])
KeyError: u'child'
You can't do it directly. There are some worarounds:
The simplest solution will be to create both on same script... If you have access to both scripts, you modified them to return data object and plot them together.
If you still have the chance to run the script, which created you're original image fig-1 (which is true, if I understand you correctly), you can save the figure as *.pickle
file and load it again for later adding additional stuff.
Suppose the following script creates fig-1:
# Script1
import numpy as np
import matplotlib.pyplot as plt
import pickle as pl
# Plot simple sinus function
fig_handle = plt.figure()
x = np.linspace(0,2*np.pi)
y = np.sin(x)
plt.plot(x,y)
With the following snippet, you can dump the plot (more precise the matplotlib.figure.Figure
object) as eg fig_handle
in a *.pickle
file
# Save figure handle to disk
pl.dump(fig_handle, open('sinus.pickle','wb'))
You can now load the figure_handle
object again in a seperate script
# Script2
import matplotlib.pyplot as plt
import pickle as pl
import numpy as np
# Load figure from disk and display
fig_handle = pl.load(open('sinus.pickle','rb'))
and even retrieve or manipulate data from it
x_old = fig_handle.axes[0].lines[0].get_data()[0]
y_old = fig_handle.axes[0].lines[0].get_data()[1]
x_new = x_old * .75 + 1
y_new = y_old * -.35
plt.plot(x_old, y_old)
plt.plot(x_new, y_new)
so you can get your new plot overlayed on the data of the original plot
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.