Search code examples
pythonnumpymatplotlibenumerate

Is there a way to plot two graphs at once using matplotlib in python?


I'm trying to simulate the following systems of chemical reactions over time, calculating and plotting how the numbers of each molecule type changes over time:

1S + 0T + 0U --> 0S + 0T + 0U
2S + 0T + 0U --> 0S + 1T + 0U 
0S + 1T + 0U --> 2S + 0T + 0U
0S + 1T + 0U --> 0S + 0T + 1U   

Because S is used in two reactions, being consumed in one and produced in another it kind of skews the results when I plot them. At the moment the code I've got to do the plotting is as follows:

for i, label in enumerate(['S', 'T', 'U']):
    plt.plot(popul_num_all[:, i], label=label)
plt.legend()
plt.tight_layout()
plt.show()

That produces the following plot enter image description here

This plot is created from the elements of an array: popul_num = np.array([S, T, U]) where I've used iteration to update and store the new values of molecule numbers over time

But the line for S just looks especially bad, Is there a way to separate the lines of S being plotted on one graph, and then the lines of T and U being plotted on a second?

Would the easiest way be to just write two enumerate functions one for S and a second for T and U ?


Solution

  • You can try subplots

    fig, (ax1, ax2) = plt.subplots(1, 2)
    
    ax1.plot(popul_num_all[:, 0], label='S')
    ax1.legend()
    
    for i, label in enumerate(['T', 'U']):
        ax2.plot(popul_num_all[:, i+1], label=label)
    
    ax2.legend()
    plt.tight_layout()
    plt.show()