Python For Quantum Mechanics #
Cheatsheet: Week 5 #
Making a Plot#
Making a plot:
Plotting a line between points with \(x\)-coordinates array_of_x_coords_1 and \(y\)-coordinates array_of_y_coords_1, and another line between points with \(x\)-coordinates array_of_x_coords_2 and \(y\)-coordinates array_of_y_coords_2, and another…
plt.plot(array_of_x_coords_1, array_of_y_coords_1, array_of_x_coords_2, array_of_y_coords_2, ...)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html
Displaying a plot:
plt.show()Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.show.html
Formatting#
Formatting a Line:
Making a plot with
line coloured
my_colour(string),line width as
my_linewidth(float),line style
my_linestyle(string), andmarker as
my_marker(string).
plt.plot(array_of_x_coords, array_of_y_coords, c=my_colour, lw=my_linewidth, ls=my_linestyle, marker=my_marker)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html
Adding errorbars with
\(x\) error bar of size
x_error,\(y\) error bar of size
y_error, anderror bar cap of size
my_capsize:
plt.errorbar(array_of_x_coords, array_of_y_coords, c=my_colour, lw=my_linewidth, ls=my_linestyle, marker=my_marker, xerr=x_error, yerr=y_error)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.errorbar.html
Formatting Axes:
Setting \(x\)-limits
leftandrightand \(y\)-limitsbottomandtop:plt.xlim((left,right))Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xlim.html
plt.ylim((bottom,top))Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ylim.html
Changing ticks to
my_xticksandmy_ytickswith labelsmy_xlabelsandmy_ylabels:plt.xticks(ticks=my_xticks, labels=my_xlabels)Documnetation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xticks.html
plt.yticks(ticks=my_yticks, labels=my_ylabels)Documnetation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.yticks.html
Adding grid lines
plt.grid()Documnetation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.grid.html
Labels:
Adding a title
plt.title('This is the Title')
Labeling axes
plt.xlabel('This is the x axis')plt.ylabel('This is the y axis')
Introducing legends
Give line a name using the
labelkeyword when plotting and set equal to a stringplt.legend()Documnetation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html
Annotations and adding lines
Adding vertical line at
x_coordfrombottom_limandtop_limplt.vlines(x_coord, bottom_lim, top_lim, c=my_colour, lw=my_linewidth, ls=my_linestyle)Documnetation: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.vlines.html
Adding horizontal line at
y_coordfromleft_limandright_limplt.hlines(y_coord, left_lim, right_lim, c=my_colour, lw=my_linewidth, ls=my_linestyle)Documnetation: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hlines.html
Annotating a point (
x_pos,y_pos) with text at position (x_text,y_text) with an arrow between with stylemy_arrowstyleplt.annotate('annotating text here', (x_pos,y_pos), c=my_colour, xytext=(x_text,y_text), arrowprops={'arrowstyle':my_arrowstyle, 'lw':my_linewidth, 'ls':my_linestyle})https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html
Log Plots:
Making log-log plots
plt.loglog(array_of_x_coords, array_of_y_coords, c=my_colour, lw=my_linewidth, ls=my_linestyle, marker=my_marker)Documnetation: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.loglog.html
Making semi-log plots
plt.semilogy(array_of_x_coords, array_of_y_coords, c=my_colour, lw=my_linewidth, ls=my_linestyle, marker=my_marker)Documnetation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.semilogy.html
plt.semilogx(array_of_x_coords, array_of_y_coords, c=my_colour, lw=my_linewidth, ls=my_linestyle, marker=my_marker)Documnetation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.semilogx.html
Figure Object#
Creating a figure
figwithwidthandheightfig = plt.figure(figsize=(width,height))Adding axes
axto figure with proportio of figure, position and size asleft,bottom,width, andheightax = fig.add_axes([left, bottom, width, height])
Documnetation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html
Adjusted functions
|
|
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Saving an image
Save
figas first_image.pngfig.savefig('first_image.png')
Multiple Plots#
Making sub-plots using
plt.subplot()Quickly create subplots in a
rows\(\times\)columnsshape and enable the axis numberinstance_numplt.subplot(rows, columns, instance_num)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot.html
plt.suptitle('This is the Overall Title')Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.suptitle.html
Plots in Plots
Can call
fig.add_axes()to add multiple sets of axes.
Making sub-plots using
fig.add_subplot()fig.version ofplt.subplotfig.add_subplot(rows, columns, instance_num)To give
hgapandvgapof horizontal and verticle space between plots usefig.subplots_adjust(hspace=hgap, wspace=vgap)Documentation: https://matplotlib.org/3.3.4/api/_as_gen/matplotlib.figure.Figure.html
Making sub-plots using
plt.subplots()Can create a figure and set axes that share/don’t share axes according to
bool_xandbool_yusingfig,ax = plt.subplots(2,2,sharex=bool_x,sharey=bool_y)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html
Other Plots#
Histogram
A histogram of
my_data,my_binsnumber of bins (or an array giving the bin edges), and with count number or density deternmined byden_boolis created usingax.hist(my_data, density=den_bool, bins=my_bins, color=my_colour, orientation=my_orientation)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.hist.html
Scatter Plot
A scatter plot of points with coordinates (
my_data_x,my_data_y)ax.scatter(my_data_x, my_data_y, c=my_colour, marker=my_marker)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.scatter.html
Bar Chart
A bar chart with bar labels
my_labels, heightsmy_data, widthsmy_width, and coloursmy_colours.ax.bar(my_labels, my_data, width=my_width, color=my_colours)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html
A horizontal bar chart with bar labels
my_labels, widthsmy_data, heightsmy_height, and coloursmy_colours.ax.barh(my_labels, my_data, height=my_height, color=my_colours)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.barh.html
Pie Chart
A pie chart of
data, labeled asmy_labelswith coloursmy_colours, exploded byexplode_arraywith shadow determined byshadow_bool.ax.pie(data, labels=my_labels, colors=my_colours, explode=explode_array, shadow = shadow_bool)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.pie.html
3D Plots#
Line the 3D space
Adding the
projection='3d'as a keyword designation infig.add_axes()creates anAxes3Dobject.Plotting points 3D line through points (
x_array,y_array,z_array)ax.plot3D(x_array, y_array, z_array)Documentation: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html
Heat maps
Create an image
imof a heatmap ofZ_meshon axismy_axaccoding to the colourmapmy_mapwithim = my_ax.imshow(Z_mesh, cmap=my_map).Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html
Add a colourbar shrunk by
my_shrinkto the figure withfig.colorbar(im, ax=my_ax, shrink=my_shrink).Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.colorbar.html
Set a limit of
my_vmintomy_vmaxonthe colour values usingim.set_clim(vmin=my_vmin, vmax=my_vmax).Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html
Surface plots
Three different types of surfaceplots of (
X_mesh,Y_mesh,Z_mesh) in 3D:ax.plot_surface(X_mesh, Y_mesh, Z_mesh),ax.plot_wireframe(X_mesh, Y_mesh, Z_mesh), andax.contour3D(X_mesh, Y_mesh, Z_mesh)
Change angle of view to angles
my_azimandmy_elevax.view_init(azim=my_azim, elev=my_elev)Documentation: https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.mplot3d.axes3d.Axes3D.html
5.7 Animations#
Changing to an interactive backend
%matplotlib notebookmakes interactive plots%matplotlib inlineis default and makes noninteractive plots
Making an initialisation function
An empty plot is first performend using
line, = ax.plot([], [])An function
init()function which will change the data plotted toxandyusingline.set_data(x,y)and will returnline,.
Making an animation function
The animate function
animate(i)will be called for each frame of the animation and will take in frame numberi. This will update the plotted values usingline.set_data()again, once again returningline,.Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.lines.Line2D.html
Animating a plot
Animation requires us to import a function.
from matplotlib.animation import FuncAnimation
To animate
figwithmy_frame_numnumber of frames, a interval ofmy_intermilliseconds between frames, and a repeat delay ofmy_delaymilliseconds.anim = FuncAnimation(fig, animate, init_func=init, frames=my_frame_num, interval=my_inter, repeat_delay=my_delay, blit=True)Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html
Saving an animation
Tutorial 5#
Noise in qubits
Particle in a Box
Normal Distribution
Monte Carlo \(\pi\) Estimation
Ball Animation
Exercises 5#
Settlers of Histogram
Normal Distribution
Particle in a Box
Plotting a Sphere
Snake Animation