使用一个“plot”调用绘制多条曲线时的一个图例条目

Tom*_*eus 2 python matplotlib

我正在通过使用一个plot调用绘制多条曲线来创建一个网格:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

x = np.array([[0,1], [0,1], [0,1]])
y = np.array([[0,0], [1,1], [2,2]])

ax.plot([0,1],[0,2], label='foo', color='b')

ax.plot(x.T, y.T, label='bar', color='k')

ax.legend()

plt.show()
Run Code Online (Sandbox Code Playgroud)

生成的图例具有与曲线一样多的“条形”条目(见下文)。我希望每次plot调用只有一个图例条目(在这种情况下只有一次“bar”)。

我想要这样我可以有其他绘图命令(例如绘制'foo'曲线的那个),如果它们有标签,它们的曲线会自动包含在图例中。我特别想避免在构建图例时手动选择句柄,而是使用 matplotlib 的功能通过是/否在绘图时包含标签来处理这个问题。我怎样才能做到这一点?

在此处输入图片说明

Imp*_*est 6

这是一种可能的解决方案:您可以使用下划线不会生成图例条目的事实。因此,将除第一个标签之外的所有标签设置为"_"禁止出现在图例中的标签。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

x = np.array([[0,1], [0,1], [0,1]])
y = np.array([[0,0], [1,1], [2,2]])

ax.plot([0,1],[0,2], label='foo', color='b')

lines = ax.plot(x.T, y.T, label='bar', color='k')
plt.setp(lines[1:], label="_")
ax.legend()

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


She*_*ore 5

以下是使用现有图例手柄和标签的一种方法。您首先获得三个handles, labels,然后只显示第一个。通过这种方式,您不仅可以控制手柄的放置顺序,还可以控制在绘图上显示的内容。

ax.plot(x.T, y.T,  label='bar', color='k')
handles, labels = ax.get_legend_handles_labels()
ax.legend([handles[0]], [labels[0]], loc='best')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

另一种方法,其中图例取自特定图(线集)——ax1在本例中

ax1 = ax.plot(x.T, y.T,  label='bar', color='k')
plt.legend(handles=[ax1[0]], loc='best')
Run Code Online (Sandbox Code Playgroud)

用两个数字将其扩展到你的问题

ax1 = ax.plot([0,1],[0,2], label='foo', color='b')
ax2 = ax.plot(x.T, y.T,  label='bar', color='k')
plt.legend(handles=[ax1[0], ax2[1]], loc='best')
Run Code Online (Sandbox Code Playgroud)

另一种替代方案是使用 for 循环,如 @SpghttCd 建议的那样

for i in range(len(x)):
    ax.plot(x[i], y[i], label=('' if i==0 else '_') + 'bar', color='k')

ax.legend()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述