LEGENDS, TITLES AND LABELS
In this tutorial, we are going to be learning about legends, titles and labels within matplotlib.
Why Legends, Titles and Labels?
So far we have learned about graphs that have basic meaning and simple context, but it’s always a good idea to have a title, label as well as a legend, especially if you have more than one data content to be compared.
Defining Legends, Titles and Labels
Just like the excel graphs, matplotlib has an in built feature for having legends on charts. You can place a legend in or out of the graph depending on your choice. You can even play around with the legend position.
In order to add the legend method you need to declare the legend() in your code. Similarly, title in Matplotlib is a text area at the top of the Graph which shows the context of the graph. Labels is the information that is displayed on the legend, without the labels legends would be empty. Let’s create a graph of multiple data sets and see how to differentiate between them:
from matplotlib import pyplot as plt #drawing simple plot x = [0,2,3] y = [0,8,16] #drawing multiple plots x2 = [0,2,3] y2 = [0,15,30] plt.plot(x,y, label='first set') plt.plot(x2,y2, label='second set') #Labelling Graphs plt.title('Main Graph') plt.ylabel('y axis') plt.xlabel('x axis') plt.legend() #showing the plot plt.show();
Make sure you add the legend() function in order to see the labels defined for multiple data sets. Without this function, you won’t be able to see the labels.
Legend Outside the Graph
You can place a legend outside a graph by simply using some attribute within the legend() function by:
plt.legend(loc="center", bbox_to_anchor=(0.5, -0.2), shadow=True, ncol=2)
Above, you can see that there are some attributes that are dedicated to position the legend box in a certain position, these attributes are:
- loc: is used to set the location of the legend by location string and location code. These are:
- ‘best’ 0
- ‘upper right’ 1
- ‘upper left’ 2
- ‘lower left’ 3
- ‘lower right’ 4
- ‘right’ 5
- ‘center left’ 6
- ‘center right’ 7
- ‘lower center’ 8
- ‘upper center’ 9
- ‘center’ 10
- bbox_to_anchor: is a 2-Tuple (x, y) or 4-Tuple (x, y, width, height) set of position points that works with the loc attribute and is used in negative and positive numbers to set the location.
- Shadow: attribute is used for setting the shadow of the legend() box. It has two values True or False.
- ncols: This attribute tells the user about the number of columns a legend box will have.
Let’s create an example where we will place the legend box outside the graph at bottom.
from matplotlib import pyplot as plt #drawing simple plot x = [0,2,3] y = [0,8,16] #drawing multiple plots x2 = [0,2,3] y2 = [0,15,30] plt.plot(x,y, label='first set') plt.plot(x2,y2, label='second set') #Labelling Graphs plt.title('Main Graph') plt.ylabel('y axis') plt.xlabel('x axis') plt.legend(loc="center", bbox_to_anchor=(0.5, -0.2), shadow=True, ncol=2) #showing the plot plt.show()