Week 2 - Syntax
Printing Outputs in Python
X = f”<text> {<replacement field>} <text>” - used to save string as a variable
f”<text> {<expression> = :<format specification>} <text>”
Format specifications control the formatting of the replacement field.
Syntax:
:<align><width><sep>.<precision><type>
align: alignment of text within the space
<, forces the replacement field text to be left aligned
>, forces the replacement field text to be right aligned
^, forces the replacement field text to be centred
width: the minimum total field with, integer
sep: the separator character for numbers (“,” or “_”)
, formats a number to include commas separators
_ formats a number to include underscores as separators
.precision: determines how many digits are displayed for floats
e, 1 digit before and p digits after the decimal point
f, rounds the number to p decimal places
g, rounds the number to p significant digits
type: the type of presentation to use based on data type
s, (string)
d, (decimal)
e, (floating point as an exponent “e”)
f (floating point number)
g (floating point with significant figures)
\n - used to print a new line
{{}} - used to print curly braces
Data Visualisation Basics in Python
import matplotlib.pyplot as plt - used to import the submodule pyplot from the library needed to draw graphs
plt.show() - required at the end of code chunks and Python scripts to display all figures created in the code chunk.
plt.plot(<x>,<y>)
x: array of independent variable values
y: array of dependent variable values, must have the same number of elements as x
If you provide a single array then it will assume that it is the y-values, and automatically generates the x-values for you. Since Python ranges start at 0, the automatically generated x-values have the same length as the provided y but start at zero
If you provide a 2D array with multiple columns as either the dependent variable or both the dependent and independent variable, Python assumes that each column is a line and automatically plots each column as a separately with different colours.
plt.plot(x,y, ‘<format string’>)
format string: string that indicates the colour, line type, and marker shape, refer to Figure 2.12, Figure 2.13 and Figure 2.14 for options.
plt.plot(x,y, <formatting style> = ‘<option>’)
optional formatting style arguments are:
Description | formatting style | Formatting options |
Line style | linestyle or ls |
|
Line colour | color or c |
|
Line width | linewidth or lw | Number |
Marker shape | marker |
|
Marker size | markersize or ms | Number |
Colour of marker edges | markeredgecolour or mec | Same as other colour |
Colour of marker faces | markerfacecolour or mfc | Same as other colour |
Function | Details |
Title and axis labels | plt.title(“<title>”, size = <font size>) - used to add a title plt.xlabel(“<x-axis label>”, size = <font size>) - used to add a x-axis label plt.ylabel(“<y-axis label>”, size = <font size>) - used to add a y-axis label |
Legend | plt.plot(x, y, label = “<label 1>”) - label for the first plot series plt.plot(x, y, label = “<label 2>”) - label for the second plot series plt. legend(loc = “<location>”) - location of the legend |
Grid lines | plt.grid(axis = “<axis option>”, <formatting>)
|
Axis limits | plt.axis([<xmin>, <xmax>, <ymin>, <ymax>]) plt.xlim(<xmin>,<xmax>) plt.ylim(<ymin>, <ymax>) |
Axis ticks | plt.xticks(<ticks>, <labels>) plt.yticks(<ticks>, <labels>)
|
Error bars | plt.errorbar(x, y, yerr = <yerr>)
|
Text label | plt.text(x, y, “<text>”)
|
Horizontal line | plt.axhline(<y>)
|
Vertical line | plt.axvline(<x>)
|
“”
Mathematical expressions | Syntax |
Foreign alphabets | \\alpha, \\beta, \\delta, \\Delta etc. |
Mathematical symbols | \\times, \\degree |
Super- and sub-scripts | ^{superscript}, _{subscript} |
Mathematical formatting | \\sqrt{}, \\frac{}{}, |
plt.figure(<figure number>, layout = <layout options>)
figure number: unique identifier for the figure; if a figure with the specified figure number does not exist, plt.figure() creates a new figure, if a figure with the specified figure number does exist, plt.figure() activates the existing figure.
plt.subplot(<m>, <n>, <p>) -plots multiple plots on the same figure. This function divides the current figure into an m-by-n grid and creates axes in the position specified by p.
m - number of grid rows
n - number of grid columns
p - grid position for the new axes, a scalar (counts across rows, then down columns)
plt.suptitle(<figure title>) - function can be used in conjunction with this to add a title to the entire figure
plt.figure() - function to help avoid overlapping axes decorations that are often caused by plotting multiple plots on the same figure.
plt.xscale(“<axis scale>“)
plt.yscale(“<axis scale>”)
axis scale:options are linear, log, symlog, logit
Data Visualisation Charts in Python
Chart | Python Syntax |
Histogram | plt.hist(<variable>, <bins>) • variable: array of numerical variable values • bins: the number of equal-width bins in the range, or a list of the bins that will be used |
Boxplot | plt.boxplot(<variable>) • variable: the numerical variable to plot |
Violin plot | plt.violinplot(<variable>) • variable: array of numerical variable values |
Scatterplot | plt.plot()with formatting styles or a format string to customise the marker shape |
Line chart | plt.plot() |
Connected scatterplot | plt.plot()with formatting styles or a format string to customise the marker shape and line style |
Scatterplot with model | multiple plt.plot()with formatting styles or a format string to customise the marker shape and the line style of each plot |
Bubble chart (using plt.scatter()) | plt.scatter(<x>, <y>, s = <s>, alpha = <alpha>) • x: array of independent variable values • y: array of dependent variable values • s: marker size (the third variable), must have the same number of elements as x and y • alpha: transparency ratio |
Bar chart | plt.bar(<x>, <y>) • x: array of categorical variable values • y: array of numerical variable values |
Multiple boxplots | plt.boxplot(<y>) plt.xticks(np.arange(1,np.size(x)+1),<x>) • y: array of numerical variable values • x: array of categorical variable values |
Multiple violin plots | plt.violinplot(<y>) plt.xticks(np.arange(1,np.size(x)+1),<x>)
|