Friday, December 27, 2024
Google search engine
HomeLanguagesMatplotlib.axes.Axes.get_legend_handles_labels() in Python

Matplotlib.axes.Axes.get_legend_handles_labels() in Python

Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.

matplotlib.axes.Axes.get_legend_handles_labels() Function

The Axes.get_legend_handles_labels() function in axes module of matplotlib library is used to return the handles and labels for legend.

Syntax: Axes.get_legend_handles_labels(self)

Parameters: This method does not accepts any parameters.

Return: This function return the handles and labels for legend.

Below examples illustrate the matplotlib.axes.Axes.get_legend_handles_labels() function in matplotlib.axes:

Example 1:




# Implementation of matplotlib function  
import matplotlib.pyplot as plt
import numpy as np
     
fig, ax = plt.subplots()
ax.plot([1, 6, 3, 8, 34, 13, 56, 67], color ="green")
  
h, l = ax.get_legend_handles_labels()
# print(h, l)
text ="Legend is present"
if h ==[]:
    text ="No legend present"
else:
    text+="and labels are : "+str(l)
      
ax.text(2.5, 60, text, fontweight ="bold")
fig.suptitle('matplotlib.axes.Axes.get_legend_handles_labels()\
 function Example\n', fontweight ="bold")
fig.canvas.draw()
plt.show()


Output:

Example 2:




# Implementation of matplotlib function
import numpy as np
np.random.seed(19680801)
import matplotlib.pyplot as plt
   
   
fig, ax = plt.subplots()
for color in [ 'tab:green', 'tab:blue', 'tab:orange']:
    n = 70
    x, y = np.random.rand(2, n)
    scale = 1000.0 * np.random.rand(n)
    ax.scatter(x, y, c = color, s = scale, label = color,
               alpha = 0.35)
   
ax.legend()
ax.grid(True)
  
h, l = ax.get_legend_handles_labels()
print(h, l)
text ="    Legend is present"
if h ==[]:
    text ="No legend present"
else:
    text+=" and labels are : \n"+str(l)
      
ax.text(0.15, 0.45, text, fontweight ="bold")
fig.suptitle('matplotlib.axes.Axes.get_legend_handles_labels()\
 function Example\n', fontweight ="bold")
fig.canvas.draw()
plt.show()


Output:

RELATED ARTICLES

Most Popular

Recent Comments