在子图中共享颜色和标签

Share color and labels on subplots

我正在尝试为相同的点创建共享相同颜色和标签的子图。我在下面有一个小例子。 每个点都有一个整数标签,以及一个用于标记和过滤的方向字符串。为了在不为每个标签创建单个散点的情况下显示正确的标签,我在图例中使用了 (handle, label) 选项。 (在我的数据中有超过3个方向)

我的问题是下面的代码显示了过滤后数据的错误标签,并且显示了另一种颜色。我怎么能

我知道 matplotlib 给出了不同句柄的列表,如果只有 2 个,则使用方向列表的前 2 个条目。我只是不知道是否有办法使用标签整数来获得正确的方向。 下面的代码图:

PS: 这是我的第一个问题,如有错误请见谅。

import numpy as np
import matplotlib.pyplot as plt

X = np.arange(0, 12)
Y = X
labels = np.array([x % 3 for x in X])
directions = ['left', 'right', 'up']*4

right_only = np.array([True if direc in ['right', 'up'] else False for direc in directions])

fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, sharey='all', sharex='all')

scatter = ax1.scatter(X, Y, c=labels)
ax1.legend(handles=scatter.legend_elements()[0], labels=directions)

scatter2 = ax2.scatter(X[right_only], Y[right_only], c=labels[right_only])
ax2.legend(handles=scatter2.legend_elements()[0], labels=directions)

为了使右图散点的颜色与左图一致,您可以使用“vmin=..., vmax=...”并将它们设置为最小值和最大值标签数组上的值。这将使它们之间的 cmap 范围保持不变。

对于绘图之间的相同标签,您需要删除不属于“right_only”的索引。对我有用的是使用“np.delete(directions, ~right_only)”,它从“directions”列表中删除了“right_only”的错误索引。

这是我所做的:

import numpy as np
import matplotlib.pyplot as plt

X = np.arange(0, 12)
Y = X
labels = np.array([x % 3 for x in X])
directions = ['left', 'right', 'up']*4

right_only = np.array([True if direc in ['right', 'up'] else False for direc in directions])

fig, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, sharey='all', sharex='all')

scatter = ax1.scatter(X, Y, c=labels)
ax1.legend(handles=scatter.legend_elements()[0], labels=directions)

scatter2 = ax2.scatter(X[right_only], Y[right_only], c=labels[right_only], vmin=np.min(labels), vmax=np.max(labels))
ax2.legend(handles=scatter2.legend_elements()[0], labels=list(np.delete(directions, ~right_only)))