Matplotlib 简明教程

Matplotlib - Legends

一般情况下,图形中的 legend 提供沿 Y 轴描述数据的可视化表示,通常称为图形系列。它是一个包含图形中每个系列的符号和标签的框。系列可以是折线图中的线、条形图中的条等。当同一绘图上有多个数据系列时,图例很有用,而且您要区分它们。在下图中,我们可以观察绘图中的图例(用红色矩形突出显示)−

In general, a legend in a graph provides a visual representation of the data depicted along the Y-axis, often referred to as the graph series. It is a box containing a symbol and a label for each series in the graph. A series could be a line in a line chart, a bar in a bar chart, and so on. The legend is helpful when you have multiple data series on the same plot, and you want to distinguish between them. In the following image, we can observe the legend in a plot (highlighted with a red color rectangle) −

legend into

Adding legend to a matplotlib plot

要向 Matplotlib 绘图添加图例,您通常使用 matplotlib.pyplot.legend() 函数。此函数用于将图例添加到 Axes,为绘图中的元素提供可视化指南。

To add a legend to a Matplotlib plot, you typically use the matplotlib.pyplot.legend() function. This function is used to add a legend to the Axes, providing a visual guide for the elements in the plot.

Syntax

以下是此函数的语法

Following is the syntax of the function

matplotlib.pyplot.legend(*args, **kwargs)

此函数可以通过不同的方式调用,具体取决于您希望如何自定义图例。

The function can be called in different ways, depending on how you want to customize the legend.

在调用 legend() 时不传递任何额外参数,Matplotlib 会自动确定要添加到图例的元素。这些元素的标签取自绘图中的艺术家。您可以在创建艺术家时或使用 set_label() 方法指定这些标签。

Matplotlib automatically determines the elements to be added to the legend while call legend() without passing any extra arguments,. The labels for these elements are taken from the artists in the plot. You can specify these labels either at the time of creating the artist or by using the set_label() method.

Example 1

在这个示例中,图例提取创建绘图时使用的标签参数中的数据。

In this example, the legend takes the data from the label argument is used when creating the plot.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3]
y = [2, 4, 6]

# Plotting the data with labels
line, = plt.plot(x, y, label='Legend describing a single line')

# Adding a legend
plt.legend()

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')
legend ex1
Successfully Placed a legend on the Axes...

Example 2

以下是在艺术家上使用 set_label() 方法的另一种方法。

Here is the alternative way of using the set_label() method on the artist.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3]
y = [2, 4, 6]

# Plotting the data with labels
line, = plt.plot(x, y)
line.set_label('Place a legend via method')

# Adding a legend
plt.legend()

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')
legend ex2
Successfully Placed a legend on the Axes...

Manually adding the legend

您可以传递一个图例艺术家的 iterable,后跟一个图例标签的 iterable,以明确控制哪些艺术家具有图例条目。

You can pass an iterable of legend artists followed by an iterable of legend labels to explicitly control which artists have a legend entry.

Example 1

以下是通过列出艺术家和标签调用 legend() 函数的示例。

Here is an example of calling the legend() function by listing artists and labels.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [1, 3, 5]
y3 = [3, 6, 9]

# Plotting the data
line1, = plt.plot(x, y1)
line2, = plt.plot(x, y2)
line3, = plt.plot(x, y3)

# calling legend with explicitly listed artists and labels
plt.legend([line1, line2, line3], ['Label 1', 'Label 2', 'Label 3'])

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')
legend ex3
Successfully Placed a legend on the Axes...

Example 2

以下是仅通过列出艺术家调用 legend() 函数的示例。这种方法与前一种方法类似,但在这种情况下,标签取自艺术家的标签属性。

Here is an example of calling the legend() function only by listing the artists. This approach is similar to the previous one but in this case, the labels are taken from the artists' label properties.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3]
y1 = [2, 4, 6]
y2 = [1, 3, 5]

# Plotting the data with labels
line1, = plt.plot(x, y1, label='Label 1')
line2, = plt.plot(x, y2, label='Label 2')

# Adding a legend with explicitly listed artists
plt.legend(handles=[line1, line2])

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')
legend ex4
Successfully Placed a legend on the Axes...

Example 3

在这个示例中,我们首先绘制两组数据,然后我们通过调用 legend() 函数来添加一个图例,其中包含一个表示图例项的字符串列表。

In this example, we first plot two sets of data, and then we add a legend by calling the legend() function with a list of strings representing the legend items.

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5, 6]
y1 = [1, 4, 2, 6, 8, 5]
y2 = [1, 5, 3, 7, 9, 6]

# Plotting the data
plt.plot(x, y1)
plt.plot(x, y2)

# Adding a legend for existing plot elements
plt.legend(['First line', 'Second line'], loc='center')

# Show the plot
plt.show()
print('Successfully Placed a legend on the Axes...')
legend ex5
Successfully Placed a legend on the Axes...

Adding legend in subplots

要在每个子图中添加图例,可以在图形的每个轴对象上使用 legend() 函数。

To add the legends in each subplot, we can use the legend() function on each axes object of the figure.

Example 1

以下是一个在 matplotlib 图形的每个子图中添加图例的示例。此方法在轴对象上使用 legend() 函数。

Here is an example that adds the legend to the each subplot of a matplotlib figure. This approach uses the legend() function on the axes object.

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7, 3.50]
plt.rcParams["figure.autolayout"] = True

# Sample data
x = np.linspace(-2, 2, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)

# Create the figure with subplots
f, axes = plt.subplots(3)

# plot the data on each subplot and add lagend
axes[0].plot(x, y1, c='r', label="sine")
axes[0].legend(loc='upper left')
axes[1].plot(x, y2, c='g', label="cosine")
axes[1].legend(loc='upper left')
axes[2].plot(x, y3, c='b', label="tan")
axes[2].legend(loc='upper left')

# Display the figure
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

legend ex6

Adding multiple legends in one axes

要在 Matplotlib 中的同一轴上绘制多个图例,我们可以将 axes.add_artist() 方法与 legend() 函数结合使用。

To draw multiple legends on the same axes in Matplotlib, we can use the axes.add_artist() method along with the legend() function.

Example 2

以下示例演示了如何在 matplotlib 图形的一个轴中添加多个图例。

The following example demonstrates how to add multiple legends in one axes of the matplotlib figure.

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7, 4]
plt.rcParams["figure.autolayout"] = True

# plot some data
line1, = plt.plot([1, 2, 3], label="Line 1", linestyle='--')
line2, = plt.plot([3, 2, 1], label="Line 2", linewidth=4)

# Add first legend at upper right of the axes
first_legend = plt.legend(handles=[line1], loc='upper right')

# Get the current axes to add legend
plt.gca().add_artist(first_legend)

# Add second legend at lower right of the axes
plt.legend(handles=[line2], loc='lower right')

# Display the output
plt.show()

执行上述代码,我们将得到以下输出 −

On executing the above code we will get the following output −

legend ex7