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
left
andright
and \(y\)-limitsbottom
andtop
: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_xticks
andmy_yticks
with labelsmy_xlabels
andmy_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
label
keyword 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_coord
frombottom_lim
andtop_lim
plt.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_coord
fromleft_lim
andright_lim
plt.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_arrowstyle
plt.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
fig
withwidth
andheight
fig = plt.figure(figsize=(width,height))
Adding axes
ax
to figure with proportio of figure, position and size asleft
,bottom
,width
, andheight
ax = 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
fig
as first_image.pngfig.savefig('first_image.png')
Multiple Plots#
Making sub-plots using
plt.subplot()
Quickly create subplots in a
rows
\(\times\)columns
shape and enable the axis numberinstance_num
plt.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.subplot
fig.add_subplot(rows, columns, instance_num)
To give
hgap
andvgap
of 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_x
andbool_y
usingfig,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_bins
number of bins (or an array giving the bin edges), and with count number or density deternmined byden_bool
is 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_labels
with coloursmy_colours
, exploded byexplode_array
with 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 anAxes3D
object.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
im
of a heatmap ofZ_mesh
on axismy_ax
accoding to the colourmapmy_map
withim = 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_shrink
to 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_vmin
tomy_vmaxon
the 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_azim
andmy_elev
ax.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 notebook
makes interactive plots%matplotlib inline
is 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 tox
andy
usingline.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
fig
withmy_frame_num
number of frames, a interval ofmy_inter
milliseconds between frames, and a repeat delay ofmy_delay
milliseconds.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