Customising plots

Colour, line style and width, labels, titles and legends; saving plots.

Computer Science/Informatics Practices5 questions

The essentials

A plot is easier to understand when it has clear labels, a title, a legend and suitable colours and line styles. Matplotlib provides arguments and functions to set all of these, and plots can be saved as image files.

Key points

  • Colour: color='red' or short codes such as 'r', 'g', 'b', 'k' (black).
  • Line style: linestyle='-' (solid, default), '--' (dashed), ':' (dotted), '-.' (dash-dot).
  • Line width: linewidth=3 makes a thicker line.
  • Marker: marker='o' (circle), 's' (square), '*' (star), '^' (triangle), with markersize.
  • A format string combines them: plt.plot(x, y, 'r--') draws a red dashed line.
  • Labels and title: plt.xlabel('Month'), plt.ylabel('Sales'), plt.title('Monthly sales').
  • Legend: give each plot a label, as in plt.plot(x, y, label='2024'), then call plt.legend() to show the legend box.
  • Grid: plt.grid(True). Ticks: plt.xticks() sets positions or text on the x axis.
  • Figure size: plt.figure(figsize=(8, 4)).
  • Saving: plt.savefig('sales.png') saves the current figure as an image (formats such as png, jpg and pdf). Call it before plt.show(), because show() may clear the figure.
  • With Pandas, the same options can be passed to df.plot(), such as df.plot(kind='line', color='green', title='Sales').

Exam tips

  • Remember that the label argument alone does not draw a legend; plt.legend() is needed.
  • Match the format string letters: 'g:' is a green dotted line.

Common mistakes

  • Calling plt.savefig() after plt.show() and getting a blank image.
  • Writing plt.label() instead of plt.xlabel() or plt.ylabel().

Practice questions

Practice this topic