Here’s the solution:

# Exercise 4: Visualise Results & Save
# Make a list of 100 x-values to plot the fit
xfit = linspace(0, 0.8, 100) 
yfit = slope*xfit + intercept

# Plot Fit results
plot(xfit,yfit, 'r-', label='Linear Fit')
errorbar(sqrt(length), time, fmt='o', label='Data', xerr=dl, yerr=dt)

# Label Axes
xlabel('$\sqrt{L}$ [m$^{1/2}$]')
ylabel('Period [s] ')

# Add Legend
legend(loc='best') # best location to avoid hiding data
# Save figure as png file with 300dpi
savefig('PendulumData.png', dpi=300, format='png', bbox_inches='tight')

So what’s going on ?

By now you should be able to manipulate functions and variables to make sense of the first two lines. You can check the numpy documentation for more information on the linspace function:

linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

Essentially, it will return an array (type given by dtype; automatically determined if =None) of num evenly spaced numbers over an interval starting at start and ending at stop (the stop number itself can be ommited if endpoint=False). If retstep=True it will also return the spacing between the numbers. In the first line of code, we’re therefore creating an array of 100 numbers between 0 and 0.8. Make sure you understand conceptually why “yfit” is also an array by construction.

The plot function, that we loaded from matplotlib.pyplot, is a bit more flexible in terms of its arguments, as its role is mainly graphic: simply plotting the “xfit” and “yfit” arrays we give it, with a bunch of options. See here for the full details. In this solution, we’re asking for a red line labeled “Linear Fit”.

Similarly, errorbar can take quite a number of options, detailed here. For the purpose of this exercise, we want to plot on the x-axis and on the y-axis, with appropriate errors (defined earlier), and data points shown as circles (fmt='o'). It turns out that the errors are too small compared to the scale of the graph to show properly; to check that they are really there and the code works, you can play around with the values of xerr and yerr.

Full marks are given only for a properly labeled and captioned plot, so don’t forget to set a legend and label your axes, including units (you can use with $...$). Save the output with savefig (see the documentation here) and move on to the next exercise.

Solutions to exercise 5