可以将matplotlib图形对象腌制然后检索吗?

时间:2016-07-11 10:31:31

标签: python matplotlib pickle

我正在尝试挑选一个matplotlib图形对象,以便能够在以后使用x和y数据以及标签和标题重新生成图形。这可能吗?

当尝试使用open和dump来pickle时,我得到了这个回溯:

#3rd Party Imports and built-in 
import random
import matplotlib.pyplot as plt 
import pickle as pk

#Initializing lists for x and y values. Voltage trim and current measure is our x and y in this case. 
voltage_trim = range(100, 150)
current_meas = []

# A change of parameters modelled by a multiplier in this case
multiplier = range(1,4)

# Initializing lists to store the output current if wanted     
current_storage = []


# Required for Matplotlib
plt.close()
plt.ion() #Required method call in order for interactive plotting to work 

# SPECIFY GRAPH
fig1 = plt.figure()
ax = fig1.add_subplot(1,1,1) # Creates an axis in order to have multiple lines 
plt.title('Voltage Trim Vs Current \nsome fancy sub-title here')
plt.xlabel('Voltage Trim / V')      
plt.ylabel('Current Measured/ A')
plt.grid(True)  

color_choices = ['k', 'g','r','b','k','c', 'm', 'y']  # Add more according to number of graphs 


# MAIN TEST LOOPS 

for this_mult in multiplier:    

    current_meas = [] # Clears the output list to graph with different multipier 

    #Enumerates input in order to manipulate it below      
    for index, value in enumerate(voltage_trim):  

        #Generating random current values in this case 
        current_meas.append(random.randint(0,10)*this_mult)

        print index ,'Generating results...'
        print index, value

        # Increments index so that lists match dimensiosn and graphing is possible         
        index += 1

        # Optional real time plotting function, comment out if not wanted 
        live_plotting = ax.plot(voltage_trim[:index], current_meas, color = color_choices[this_mult])#,label = 'Line'+str(this_mult)

        # A pyplot method that pauses the loop, updates the graph and continues to enable for real time graphing, set to small number to be considered insignificant 
        plt.pause(1e-124) 

        # Deletes the real time line to save memory in the loop         
        live_plotting[0].remove()

    # This is the actual storage of plot objects, specify legend label here, and all other arguments the same    
    ax.plot(voltage_trim, current_meas,color = color_choices[this_mult],marker = 'o', label = 'Line'+str(this_mult))     


    #Stores the measured current (A)    
    current_storage.append(current_meas)

    #Calls legend - must be in outer loop     
    plt.legend()

f = open('testt','wb')
pk.dump(fig1, f)
f.close() 

1 个答案:

答案 0 :(得分:5)

是。尝试

import pickle
import matplotlib.pyplot as plt

file = open('myfile', 'wb')
fig = plt.gcf()
pickle.dump(fig, file)
file.close()

然后阅读

file = open('myfile', 'rb')
pickle.load(file)
plt.show()
file.close()