📜  未显示子图外的图例 - Python (1)

📅  最后修改于: 2023-12-03 15:26:32.130000             🧑  作者: Mango

未显示子图外的图例 - Python

有时候使用Matplotlib绘图时,我们可能会遇到这样一个问题:子图外的图例没有显示出来。这通常是由于没有正确地配置Matplotlib的图例参数所致。

下面是一些可能导致此问题的原因及其解决方法:

1. 使用子图时未使用add_artist方法添加图例

当我们在一个子图中绘制多个曲线或散点图时,需要使用add_artist方法来将每个曲线或散点图的图例添加到子图外:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
line1, = ax.plot([1,2,3], [4,5,6], label='Line 1')
line2, = ax.plot([1,2,3], [6,5,4], label='Line 2')
scatter = ax.scatter([2,3,4], [5,4,3], label='Scatter')
ax.legend(handles=[line1, line2, scatter])
for artist in [line1, line2, scatter]:
    ax.add_artist(artist)
plt.show()
2. 使用子图时未在外部配置图例参数

如果我们在子图中使用了图例,但没有在外部对图例参数进行配置,则可能无法正确显示子图外的图例。可以使用figlegend方法在图形中添加图例,并通过bbox_to_anchor参数指定其位置:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
line1, = ax.plot([1,2,3], [4,5,6], label='Line 1')
line2, = ax.plot([1,2,3], [6,5,4], label='Line 2')
scatter = ax.scatter([2,3,4], [5,4,3], label='Scatter')
legend = fig.legend(handles=[line1, line2, scatter], bbox_to_anchor=(1.05, 1), loc='upper left')
plt.show()
3. 使用子图时未正确配置图例参数

如果我们在子图中使用了图例,并已在外部配置了它们的位置和参数,但仍无法正确显示子图外的图例,则可能需要重新调整图例的位置和参数。

可以使用legend方法来配置图例的位置、边框框架、透明度和其他属性。例如:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
line1, = ax.plot([1,2,3], [4,5,6], label='Line 1')
line2, = ax.plot([1,2,3], [6,5,4], label='Line 2')
scatter = ax.scatter([2,3,4], [5,4,3], label='Scatter')
legend = ax.legend(handles=[line1, line2, scatter], loc='upper right', framealpha=1)
plt.show()

这将在右上角显示图例,并更改图例框架的透明度。

综上所述,我们可以通过正确添加图例以及在外部正确配置和调整图例参数来解决“子图外的图例未显示”的问题。