Matplotlib.figure.Figure.legend () в Python

Опубликовано: 23 Марта, 2022

Matplotlib - это библиотека на Python, которая является численно-математическим расширением библиотеки NumPy. Модуль Figure предоставляет Художника верхнего уровня, Figure, который содержит все элементы сюжета. Этот модуль используется для управления интервалом по умолчанию для подзаголовков и контейнера верхнего уровня для всех элементов графика.

matplotlib.figure.Figure.legend () метод

Модуль фигуры метода legend () библиотеки matplotlib используется для размещения легенды на рисунке.

Syntax: legend(self, *args, **kwargs)

Parameters: This method accept the following parameters that are discussed below:

  • handles :This parameter is the list of Artists (lines, patches) to be added to the legend.
  • labels :This parameter is the list of labels to show next to the artists.

Returns: This method returns the matplotlib.legend.Legend instance.

Примеры ниже иллюстрируют функцию matplotlib.figure.Figure.legend () в matplotlib.figure:

Example 1:

# Implementation of matplotlib function 
import matplotlib.pyplot as plt 
    
fig, ax = plt.subplots() 
    
line1, = ax.plot([1, 2, 3], 
                 label ="Line 1"
                 color ="black",  
                 linewidth = 4
                 linestyle =":"
    
line2, = ax.plot([3, 2, 1],  
                 label ="Line 2"
                 color ="green",  
                 linewidth = 4
    
    
first_legend = ax.legend(handles =[line1],  
                         loc ="upper center"
    
ax.add_artist(first_legend) 
    
fig.legend(handles =[line2], loc ="lower center")
  
fig.suptitle("""matplotlib.figure.Figure.legend()
function Example """, fontweight ="bold") 
    
plt.show() 

Выход:

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)
   
fig.legend()
ax.grid(True)
  
fig.suptitle("""matplotlib.figure.Figure.legend()
function Example """, fontweight ="bold") 
    
plt.show() 

Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.