How it works...

Here is the explanation for each of the eleven plots:

  • Plot1: Label is specified as part of the line plot itself.
  • Plot2: Label is specified as a method on the line axes, after the line object is created.
  • Plot3: Labels are defined as a list on the plt.legend() command itself.
  • Plot4: Handles (axes objects) and labels are passed on as tuples to the plt.legend() function.
  • Plot5: Only two out of three handles are passed on to plt.legend(), so line_3 is not shown in the legend.
  • Plot6: Similar to plot five, but both handles and labels are passed on to the plt.legend().
  • Plot7: A patch is used as a label. mpatches.Patch() creates a red patch.
  • Plot8: Plots two different categories of data and labels them separately.
  • Plot9: Plots the legend on top of the plot, with labels spreading from left to right, and not overlapping with the title. plt.legend(bbox_to_anchor=(0, 1.02, 1., .102), ncol=2, mode="expand", borderaxespad=0.5) places labels on top of the plot using bbox_to_anchor (0 from left, 1.02 from bottom, 1.0 is the width, and 0.102 is height, in proportion to the plot's dimensions). ncol=2 specifies that labels should be placed in two columns, as opposed to two rows, which is the default.
  • Plot10: Legend is placed on the right side of the plot, again using bbox_to_anchor() co-ordinates.
  • Plot11: Splits the label into two parts and places them at different locations. Multiple calls to plt.legend() will overwrite previous legends; only the last one will prevail, so it can't be used to split and place the labels at different locations. One of them has to be placed manually with ax=plt.gca().add_artist(first_legend). plt.gca() getting the current axes, and then add_artist() adding the label on to this axis. For the second label, use the standard plt.legend().
  • Plot12: Since there is no twelfth part, we have to clean up spines, ticks, and ticklabels. Otherwise, they will show up without any plot! We will learn about spines and ticks soon in this chapter.

Here are how the plots look with the respective legends: