Data visualization with Python study guide

Star

General structure

Overview The general structure of the code that is used to plot figures is as follows:

# Plot
f, ax = plt.subplots(...)
ax = sns...

# Legend
plt.title()
plt.xlabel()
plt.ylabel()

We note that the plt.subplots() command enables to specify the figure size.


Basic plots The main basic plots are summarized in the table below:

TypeCommand and parametersIllustration
Scatter plotsns.scatterplot(
  x, y, hue, size
)
Line plotsns.lineplot(
  x, y, hue, size
)
Bar chart

Histogram
sns.barplot(
  x, y, hue
)
Box plotsns.boxplot(
  x, y, hue
)
Heatmapsns.heatmap(
  data, cmap, linecolor,
  linewidth, cbar
)

where the meaning of parameters are summarized in the table below:

CommandDescriptionUse case
hueColor of a line / point / border'red'
fillColor of an area'red'
sizeSize of a line / point4
linetypeShape of a line'dashed'
alphaTransparency, between 0 and 10.3


Advanced features

Text annotation Plots can have text annotations with the following commands:

CommandIllustration
ax.text(
  x, y, s, color
)


Additional elements We can add objects on the plot with the following commands:

TypeCommandIllustration
Lineax.axvline(
  x, ymin, ymax, color,
  linewidth, linestyle
)
ax.axhline(
  y, xmin, xmax, color,
  linewidth, linestyle
)
Rectangleax.axvspan(
  xmin, xmax, ymin, ymax,
  color, fill, alpha
)


Last touch

Legend The title of legends can be customized to the plot with the commands summarized below:

ElementCommand
Title / subtitle of the plotax.set_title('text', loc, pad)
plt.suptitle('text', x, y, size, ha)
Title of the $x$ / $y$ axisax.set_xlabel('text') / ax.set_ylabel('text')
Title of the size / colorvia ax.get_legend_handles_labels()
Caption of the plotax.text('text', x, y, fontsize)

This results in the following plot:


Double axes A plot can have more than one axis with the plt.twinx() command. It is done as follows:

ax2 = plt.twinx()


Figure saving There are two main steps to save a plot: