Python - resizing a plot in a for loop

Viewed 101

I have a for loop which calculates a value (g) from a number of datasets, and plots it in a scatter graph:

g_meanarray = []

import matplotlib.patches as mpatches

for i in range(len(dataset)):
    data=np.loadtxt(dataset[i],dtype=float,delimiter='/')
    distance=data[:,2]
    number=data[:,0]
    time=data[:,1]
    garray = []
    
    g_error = errorfunc_g(distance,time)
    error_array = np.array(g_error)
    g_res=gravity(number,time,distance)
    garray.append(g_res)
    print(error_array)
    print(garray, '\n')
    
    g_mean = np.mean(garray)
    g_meanarray.append(g_mean)
    n = i + 1

    
    plt.scatter([n,n,n,n,n],garray, c = 'green', marker='.',label = "dataset{0}".format(i)) # Plots the measured g values for each dataset
    plt.errorbar([n,n,n,n,n],g_res,yerr=error_array, linestyle="None")
    plt.title('(Figure 1) - measured gravity values by dataset')
    plt.xlabel('Dataset')
    plt.ylabel('gravity estimated (m/s^2)')
    
    plt.scatter(n,g_mean,linestyle="None", label = "dataset{0}".format(i), c = 'black') # plots the mean g value for each dataset
    plt.title('(Figure 1) - measured gravity values by dataset')
    plt.xlabel('Dataset')
    plt.ylabel('gravity estimated (m/s^2)')
    meanlegend = mpatches.Patch(color='black', label='Mean g value')
    datalegend = mpatches.Patch(color='green', label='Measured g values')
    plt.legend(handles=[datalegend, meanlegend])

I want to resize the resulting graph, but using plt.figure(figsize = (a,b)) results in six different graphs for each dataset, I want them to remain plotted on one graph. How do I do this?

Thanks

1 Answers

Try initializing your plot before the for loop and then calling plt.show() at the end, outside of the for loop.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
for i in range(10):
     ax.scatter(i,i)
     fig.set_size_inches(w=i,
                         h=i)
plt.show()
Related