Matplotlib legend in subplot

In this tutorial, we will learn how Matplotlib can be used to include legends in subplots. The legend can be added after creating the plot using the legend() function.

Syntax:

The syntax for legend in subplot is:

where, loc is used for location.

Approaches:

Following are the approaches we will use for displaying legend in the subplot in Matplotlib:

  • First, we will use the subplots() function for creating subplots in a bigger plot.
  • Then, we will use the legend() function for adding a label to the curves.
  • At last, we will show the plots by using the show()

Example 1:

In this example, we will plot the scatter graph using subplot of log10 and exponential:

Output

Matplotlib legend in subplot

Example 2:

In this example, we will plot the scatter graph using subplot of sine and cos:

Output

Matplotlib legend in subplot

Example 3:

In this example, we will plot the scatter graph using subplot of (y = x^2) and (y = x^3):

Output

Matplotlib legend in subplot

Conclusion

In this tutorial, we have discussed how to use legend in the subplot of matplotlib graphs using different methods.






Latest Courses