diff agl.py @ 4:deb3adc4e086

Add graph saving option.
author Daniel O'Connor <darius@dons.net.au>
date Mon, 11 Sep 2017 12:32:05 +0930
parents 525a66486282
children b42baa411817
line wrap: on
line diff
--- a/agl.py	Mon Sep 11 11:32:52 2017 +0930
+++ b/agl.py	Mon Sep 11 12:32:05 2017 +0930
@@ -38,6 +38,7 @@
     parser = argparse.ArgumentParser()
     parser.add_argument('-u', '--update', help = 'Update data', action="store_true")
     parser.add_argument('-g', '--graph', help = 'Produce graph', action="store_true")
+    parser.add_argument('-f', '--filename', help = 'Filename to save graph as', type = str)
     parser.add_argument('-s', '--start', help = 'Start date for graph (YYYY-MM-DD)', type = valid_date)
     parser.add_argument('-e', '--end', help = 'End date for graph (YYYY-MM-DD)', type = valid_date)
 
@@ -90,7 +91,7 @@
             date += datetime.timedelta(days = 1)
 
     if args.graph:
-        graph(cur, ['battery_charge', 'power_imported', 'power_exported', 'power_consumed', 'power_generated'], start, end)
+        graph(args.filename, cur, ['battery_charge', 'power_imported', 'power_exported', 'power_consumed', 'power_generated'], start, end)
 
 def mkdb(cur):
     cur.execute('''
@@ -149,11 +150,10 @@
     'site_cons_pv' : 'Site Consumption PV'
 }
 
-def graph(cur, cols, start, end):
+def graph(fname, cur, cols, start, end):
     import numpy
     import matplotlib
     import matplotlib.dates
-    import matplotlib.pylab
 
     colourlist = ['b','g','r','c','m','y','k']
 
@@ -205,7 +205,13 @@
             ax2lines.append([xdata, ary[:,idx + 1], names[cols[idx]], colourlist[colouridx]])
         colouridx += 1
 
-    fig = matplotlib.pylab.figure()
+    if fname == None:
+        import matplotlib.pylab
+        fig = matplotlib.pylab.figure()
+    else:
+        import matplotlib.backends.backend_agg
+        fig = matplotlib.figure.Figure(figsize = (8, 6), dpi = 75)
+
     ax1 = fig.add_subplot(111)
     ax1.set_ylabel(yaxisunits1)
 
@@ -236,7 +242,11 @@
 
     # Fudge margins to give more graph and less space
     fig.subplots_adjust(left = 0.10, right = 0.88, top = 0.95, bottom = 0.15)
-    matplotlib.pyplot.show()
+    if fname == None:
+        matplotlib.pyplot.show()
+    else:
+        canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig) # Sets canvas in fig too
+        fig.savefig(fname)
 
 def updatedb(cur, data):
     mkdb(cur)