matplotlibpython-3.10graphing

Show 2 plots at the same time


I have this code to generate the partial sums of pi (this is the part which graphs it):

plt.figure(1)
plt.plot(piresults)
plt.ylabel('value of calculated pi')
plt.xlabel('number of fractions calculated')
piresults2=[]
for result in piresults:
  piresults2.append(math.fabs((result-math.pi)/math.pi))
plt.figure(2)
plt.plot(piresults2)
plt.ylim(0,1)
plt.ylabel('error %')
plt.xlabel('number of fractions calculated')
plt.show()

But my problem is the plots dont appear at the same time

I was expecting the two plots to appear alongside each other after only using plt.show() at the end and making the figures separate. But that's not happening? They appeared separately and i had to close one to get the other


Solution

  • If they're popping up as separate windows, you could draw two plots on a single figure/window instead.

    Use plt.subplots() to create a figure that has multiple subplots (axes). Select each subplot in turn (axes[0], then axes[1]) to plot on.

    enter image description here

    piresults1 = np.linspace(3.12, 3.16)
    piresults2 = np.linspace(0.2, 0.6)
    
    #Create figure with 2 subplots ("axes")
    figure, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 3))
    
    #Get the handle of the first subplot, axes[0], and plot
    ax = axes[0]
    ax.plot(piresults1)
    ax.set_ylabel('value of calculated pi')
    ax.set_xlabel('number of fractions calculated')
    
    #Get the handle of the second subplot, axes[1], and plot
    ax = axes[1]
    ax.plot(piresults2)
    ax.set_ylim(0,1)
    ax.set_ylabel('error %')
    ax.set_xlabel('number of fractions calculated')