matplotlib - How to assign a plot to a variable and use the variable as the return value in a Python function -
i creating 2 python scripts produce plots technical report. in first script defining functions produce plots raw data on hard-disk. each function produces 1 specific kind of plot need. second script more batch file supposed loop around functions , store produced plots on hard-disk.
what need way return plot in python. want this:
fig = some_function_that_returns_a_plot(args) fig.savefig('plot_name')
but not know how make plot variable can return. possible? so, how?
you can define plotting functions
import numpy np import matplotlib.pyplot plt # example graph type def fig_barh(ylabels, xvalues, title=''): # create new figure fig = plt.figure() # plot yvalues = 0.1 + np.arange(len(ylabels)) plt.barh(yvalues, xvalues, figure=fig) yvalues += 0.4 plt.yticks(yvalues, ylabels, figure=fig) if title: plt.title(title, figure=fig) # return return fig
then use them like
from matplotlib.backends.backend_pdf import pdfpages def write_pdf(fname, figures): doc = pdfpages(fname) fig in figures: fig.savefig(doc, format='pdf') doc.close() def main(): = fig_barh(['a','b','c'], [1, 2, 3], 'test #1') b = fig_barh(['x','y','z'], [5, 3, 1], 'test #2') write_pdf('test.pdf', [a, b]) if __name__=="__main__": main()
Comments
Post a Comment