Open In App

Matplotlib legend in subplot

Last Updated : 28 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how Matplotlib can be employed to add legends in subplots. We can add the legend after making the plot  by using legend() function

Syntax:

axes[position].legend(loc='best')

where, loc is the location and the  ‘best’ places the legend at the location

Approach:

  • Use subplots() method to create subplots in a bigger plot.
  • Use legend() method to add label to the curves.
  • Then show the plots using show() method.

Example 1:

In this example,  the scatter graph is plot with subplots of sine and cos.

Python3




# importing modules
from matplotlib import pyplot
import numpy
  
# assign value to x axis
x_axis = numpy.arange(1, 20, 0.5)
  
# get the value of log10
y_axis_log10 = numpy.log10(x_axis)
  
# get the value of exp
y_axix_exp = numpy.exp(x_axis)
  
# create subplots using subplot() method
fig, axes = pyplot.subplots(2)
  
# depicting the visualization
axes[0].plot(x_axis, y_axis_log10, color='green', label="log10")
axes[1].plot(x_axis, y_axix_exp, color='blue', label="exp")
  
# position at which legend to be added
axes[0].legend(loc='best')
axes[1].legend(loc='best')
  
# display the plot
pyplot.show()


Output:

Example 2:

In this example, the scatter graph is plot with subplots of (y=x^2) and (y=x^3).

Python3




# importing modules
from matplotlib import pyplot
import numpy
  
# assign value to x axis
x_axis = numpy.arange(-2, 2, 0.1)
  
# get the value of sine
y_axis_sine = numpy.sin(x_axis)
  
# get the value of cos
y_axix_cose = numpy.cos(x_axis)
  
# create subplots using subplot() method
fig, axes = pyplot.subplots(2)
  
# depicting the visualization(scatter)
axes[0].scatter(x_axis, y_axis_sine, color='green', marker='*', label="sine")
axes[1].scatter(x_axis, y_axix_cose, color='blue', marker='*', label="cos")
  
# position at which legend to be added
axes[0].legend(loc='best')
axes[1].legend(loc='best')
  
# display the plot
pyplot.show()


Output: 

Example 3:

Python3




# importing modules
from matplotlib import pyplot
  
# assign value to x axis
x_axis = list(range(-10, 10))
  
# get the value of x*x
y_axis1 = [x*x for x in x_axis]
  
# get the value of x*x*x
y_axix2 = [x*x*x for x in x_axis]
  
# create subplots using subplot() method
fig, axes = pyplot.subplots(2)
  
# depicting the visualization
axes[0].scatter(x_axis, y_axis1, color='green', marker='*', label="y=x^2")
axes[1].scatter(x_axis, y_axix2, color='red', marker='*', label="y=x^3")
  
# position at which legend to be added
axes[0].legend(loc='best')
axes[1].legend(loc='best')
  
# display the plot
pyplot.show()


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads