Matplotlib legend in subplot
Last Updated :
28 Nov, 2021
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
from matplotlib import pyplot
import numpy
x_axis = numpy.arange( 1 , 20 , 0.5 )
y_axis_log10 = numpy.log10(x_axis)
y_axix_exp = numpy.exp(x_axis)
fig, axes = pyplot.subplots( 2 )
axes[ 0 ].plot(x_axis, y_axis_log10, color = 'green' , label = "log10" )
axes[ 1 ].plot(x_axis, y_axix_exp, color = 'blue' , label = "exp" )
axes[ 0 ].legend(loc = 'best' )
axes[ 1 ].legend(loc = 'best' )
pyplot.show()
|
Output:
Example 2:
In this example, the scatter graph is plot with subplots of (y=x^2) and (y=x^3).
Python3
from matplotlib import pyplot
import numpy
x_axis = numpy.arange( - 2 , 2 , 0.1 )
y_axis_sine = numpy.sin(x_axis)
y_axix_cose = numpy.cos(x_axis)
fig, axes = pyplot.subplots( 2 )
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" )
axes[ 0 ].legend(loc = 'best' )
axes[ 1 ].legend(loc = 'best' )
pyplot.show()
|
Output:
Example 3:
Python3
from matplotlib import pyplot
x_axis = list ( range ( - 10 , 10 ))
y_axis1 = [x * x for x in x_axis]
y_axix2 = [x * x * x for x in x_axis]
fig, axes = pyplot.subplots( 2 )
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" )
axes[ 0 ].legend(loc = 'best' )
axes[ 1 ].legend(loc = 'best' )
pyplot.show()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...