I figured out a relatively simple way (but a bit unconventional) to save my matplotlib metrics. I do like this:
import libscript import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2*np.pi*t)
with the save_plot function defined as follows (simple version for understanding the logic):
def save_plot(fileName='',obj=None,sel='',ctx={}): """ Save of matplolib plot to a stand alone python script containing all the data and configuration instructions to regenerate the interactive matplotlib figure. Parameters ---------- fileName : [string] Path of the python script file to be created. obj : [object] Function or python object containing the lines of code to create and configure the plot to be saved. sel : [string] Name of the tag enclosing the lines of code to create and configure the plot to be saved. ctx : [dict] Dictionary containing the execution context. Values for variables not defined in the lines of code for the plot will be fetched from the context. Returns ------- Return ``'done'`` once the plot has been saved to a python script file. This file contains all the input data and configuration to re-create the original interactive matplotlib figure. """ import os import libscript N_indent=4 src=libscript.get_src(obj=obj,sel=sel) src=libscript.prepend_ctx(src=src,ctx=ctx,debug=False) src='\n'.join([' '*N_indent+line for line in src.split('\n')]) if(os.path.isfile(fileName)): os.remove(fileName) with open(fileName,'w') as f: f.write('import sys\n') f.write('sys.dont_write_bytecode=True\n') f.write('def main():\n') f.write(src+'\n') f.write('if(__name__=="__main__"):\n') f.write(' '*N_indent+'main()\n') return 'done'
or by defining the save_plot function as follows (the best version using zip compression to create lighter save_plot files):
def save_plot(fileName='',obj=None,sel='',ctx={}): import os import json import zlib import base64 import libscript N_indent=4 level=9
This uses the libscript module of my own, which mainly relies on the inspect and ast modules. I can try to share it with Github if interest is expressed (at first I needed to clear a bit, and I started with Github).
The idea of this save_plot and libscript is to extract the python commands that create the drawing (using the inspect module), analyze them (using the ast module), to extract all variables, functions and modules import it, extract them from the execution context and serialize them as python instructions (the code for the variables will be like t=[0.0,2.0,0.01] ... and the code for the modules will be like import matplotlib.pyplot as plt ...) added to the drawing instructions. The resulting python instructions are saved as python script whose execution will rebuild the original matplotl drawing ib.
As you can imagine, this works well for most (if not all) matplotlib digits.
Astrum42 Nov 07 '17 at 14:48 2017-11-07 14:48
source share