1

I need to plot changing molecule numbers against time. But I'm also trying to investigate the effects of parallel processing so I'm trying to avoid writing to global variables. At the moment I have the following two numpy arrays tao_all, contains all the time points to be plotted on the x-axis and popul_num_all which contains the changing molecule numbers to be plotted on the y-axis.

The current code I've got for plotting is as follows:

for i, label in enumerate(['Enzyme', 'Substrate', 'Enzyme-Substrate complex', 'Product']):
    figure1 = plt.plot(tao_all, popul_num_all[:, i], label=label)
plt.legend()
plt.tight_layout()
plt.show()

I need to encapsulate this in a function that takes the above arrays as the input and returns the graph. I've read a couple of other posts on here that say I should write my results to an axis and return the axis? But I can't quite get my head around applying that to my problem?

Cheers

Mike5298
  • 377
  • 1
  • 13
  • The question was answered in https://stackoverflow.com/questions/43925337/matplotlib-returning-a-plot-object. – Roohollah Etemadi Jun 27 '20 at 16:52
  • 1
    strongly suggest not returning a figure, but rather create the figure and axes outside of the function and then *pass* the axes to the function. – Jody Klymak Jun 27 '20 at 17:50
  • Hi Mike, do you need a single plot with 4 curves in it, or a grid of 4 different plots, each containing a single curve? – gboffi Jun 27 '20 at 19:17
  • About the confusion with figures' and axes' roles, I've written [an appreciated answer](https://stackoverflow.com/questions/37970424/what-is-the-difference-between-drawing-plots-using-plot-axes-or-figure-in-matpl/56629063#56629063) that maybe could help you. – gboffi Jun 27 '20 at 19:22
  • Thanks for the suggestions! I've actually solved current the problem with one of the other answers provided, But I'm going to be using quite a lot of matplotlib in my project so all suggestions are appreciated! :) – Mike5298 Jun 29 '20 at 09:32

2 Answers2

2
def plot_func(x, y):
    fig,ax = plt.subplots()
    ax.plot(x, y)
    return fig

Usage:

fig = plot_func([1,2], [3,4])

Alternatively you may want to return ax. For details about Figure and Axes see the docs. You can get the axes array from the figure by fig.axes and the figure from the axes by ax.get_figure().

Stef
  • 28,728
  • 2
  • 24
  • 52
0

In addition to above answer, I can suggest you to use matplotlib animation.FuncAnimation method if you are working with the time series and want to make your visualization better.

You can find the details here https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html

Erol Erdogan
  • 128
  • 9