📜  如何在 Matplotlib 中为所有子图创建单个图例?

📅  最后修改于: 2022-05-13 01:54:59.957000             🧑  作者: Mango

如何在 Matplotlib 中为所有子图创建单个图例?

matplotlib 中的 subplot()函数有助于在单个图形中创建子图网格。在图中,从左上角开始创建子图并按行排序。 Matplotlib 库中的图例基本上描述了图形元素。通过将图例()放置在不同的位置,可以在图形内部或外部的任何位置进行自定义和调整。有时需要为所有子图创建一个图例。下面是显示所有子图的单个图例的示例。

Subplot() 的语法:

subplot(nrows,ncols,nsubplot)

例如, subplot(2,1,1) 是表示第一个 2 行 1 列子图的图形,第一个子图位于第一行。

subplot(2,1,2) 表示位于第一列第二行的第二个子图。

图例命令语法:

legend(*args, **kwargs)

如果参数的长度,即 args 在图例命令中为 0,则它会通过调用 get_legend_handles_labels() 方法从标签属性自动生成图例。

例如, ax.legend() 相当于:

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)

get_legend_handles_labels() 方法返回两个列表的元组,即艺术家列表和标签列表。

示例 1:

Python3
# Importing required libraries
import matplotlib.pyplot as plt
import numpy as np
  
# 2 subplots in 1 row and 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
  
x1 = ['Telugu', 'Hindi', 'English',
      'Maths', 'Science', 'Social']
y1 = [45, 34, 30, 45, 50, 38]
y2 = [36, 28, 30, 45, 38, 48]
  
# Labels to use in the legend for each line
labels = ["in 2019", "in 2020"]
  
# Title for subplots
fig.suptitle('Number of Students passed in each subject\
from a class in 2019 & 2020', fontsize=20)
  
# Creating the sub-plots.
l1 = ax1.plot(x1, y1, color="green")
l2 = ax2.plot(x1, y2, color="blue")
  
ax1.set_yticks(np.arange(0, 51, 5))
ax2.set_yticks(np.arange(0, 51, 5))
  
ax1.set_ylabel('Number of students', fontsize=25)
  
  
fig.legend([l1, l2], labels=labels,
           loc="upper right")
  
# Adjusting the sub-plots
plt.subplots_adjust(right=0.9)
  
plt.show()


Python3
# Plotting sub-plots of number of 
# students passed in each subject 
# in academic year 2017-20.
import matplotlib.pyplot as plt
import numpy as np
  
plt.style.use('seaborn')  # Plot Styles
  
fig = plt.figure()
  
# 4 subplots in 2 rows and 2 columns in a figure
axes = fig.subplots(nrows=2, ncols=2)
  
axes[0, 0].bar(['Telugu', 'Hindi', 'English', 
                'Maths', 'Science', 'Social'],
               [50, 27, 42, 34, 45, 48], 
               color='g', label="Students passed in 2017")
  
axes[0, 0].set_yticks(np.arange(0, 51, 5))
  
axes[0, 1].bar(['Telugu', 'Hindi', 'English', 
                'Maths', 'Science', 'Social'],
               [50, 27, 42, 34, 45, 48], 
               color='y', label="Students passed in 2018")
  
axes[0, 1].set_yticks(np.arange(0, 51, 5))
  
axes[1, 0].bar(['Telugu', 'Hindi', 'English', 
                'Maths', 'Science', 'Social'],
               [40, 27, 22, 44, 35, 38],
               color='r', label="Students passed in 2019")
  
axes[1, 0].set_yticks(np.arange(0, 51, 5))
axes[1, 0].set_xlabel('Subjects', fontsize=25)
  
# rotating third sub-plot x-axis labels
for tick in axes[1, 0].get_xticklabels():
    tick.set_rotation(45)
  
axes[1, 0].set_ylabel(" Number of Students passed in 2017-2020", fontsize=20)
  
  
axes[1, 1].bar(['Telugu', 'Hindi', 'English',
                'Maths', 'Science', 'Social'],
               [40, 27, 32, 44, 45, 48], 
               color='b', label="Students passed in 2020")
  
axes[1, 1].set_xlabel('Subjects', fontsize=20)
axes[1, 1].set_yticks(np.arange(0, 51, 5))
  
  
lines = []
labels = []
  
for ax in fig.axes:
    Line, Label = ax.get_legend_handles_labels()
    # print(Label)
    lines.extend(Line)
    labels.extend(Label)
  
# rotating x-axis labels of last sub-plot
plt.xticks(rotation=45)
  
fig.legend(lines, labels, loc='upper right')
  
plt.show()


输出:

示例 2:

蟒蛇3

# Plotting sub-plots of number of 
# students passed in each subject 
# in academic year 2017-20.
import matplotlib.pyplot as plt
import numpy as np
  
plt.style.use('seaborn')  # Plot Styles
  
fig = plt.figure()
  
# 4 subplots in 2 rows and 2 columns in a figure
axes = fig.subplots(nrows=2, ncols=2)
  
axes[0, 0].bar(['Telugu', 'Hindi', 'English', 
                'Maths', 'Science', 'Social'],
               [50, 27, 42, 34, 45, 48], 
               color='g', label="Students passed in 2017")
  
axes[0, 0].set_yticks(np.arange(0, 51, 5))
  
axes[0, 1].bar(['Telugu', 'Hindi', 'English', 
                'Maths', 'Science', 'Social'],
               [50, 27, 42, 34, 45, 48], 
               color='y', label="Students passed in 2018")
  
axes[0, 1].set_yticks(np.arange(0, 51, 5))
  
axes[1, 0].bar(['Telugu', 'Hindi', 'English', 
                'Maths', 'Science', 'Social'],
               [40, 27, 22, 44, 35, 38],
               color='r', label="Students passed in 2019")
  
axes[1, 0].set_yticks(np.arange(0, 51, 5))
axes[1, 0].set_xlabel('Subjects', fontsize=25)
  
# rotating third sub-plot x-axis labels
for tick in axes[1, 0].get_xticklabels():
    tick.set_rotation(45)
  
axes[1, 0].set_ylabel(" Number of Students passed in 2017-2020", fontsize=20)
  
  
axes[1, 1].bar(['Telugu', 'Hindi', 'English',
                'Maths', 'Science', 'Social'],
               [40, 27, 32, 44, 45, 48], 
               color='b', label="Students passed in 2020")
  
axes[1, 1].set_xlabel('Subjects', fontsize=20)
axes[1, 1].set_yticks(np.arange(0, 51, 5))
  
  
lines = []
labels = []
  
for ax in fig.axes:
    Line, Label = ax.get_legend_handles_labels()
    # print(Label)
    lines.extend(Line)
    labels.extend(Label)
  
# rotating x-axis labels of last sub-plot
plt.xticks(rotation=45)
  
fig.legend(lines, labels, loc='upper right')
  
plt.show()

输出 :