【问题标题】:Share color and labels on subplots在子图上共享颜色和标签
【发布时间】:2021-04-21 09:09:36
【问题描述】:

我正在尝试为相同的点创建共享相同颜色和标签的子图。我在下面有一个小例子。 每个点都有一个整数标签和一个用于标记和过滤的方向字符串。为了在不为每个标签创建单个散点的情况下显示正确的标签,我在图例中使用了 (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=0, vmax=2 添加到对scatter() 的两个调用中。这样 0、1 和 2 将始终映射到相同的颜色。

标签: python matplotlib colors label


【解决方案1】:

要使右侧图上散点的颜色与左侧图一致,您可以使用“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)))

【讨论】:

  • 谢谢,这正是我想要的!不知道 vmin 和 vmax。
  • 在旁注中,我不得不为我的其他代码稍微调整一下解决方案。如果您碰巧只有一组唯一方向而不是每个值的方向,则可以这样做:labels=list(np.delete(directions, ~np.unique(labels[right_only]))) 也许这会帮助遇到相同问题的人。
猜你喜欢
  • 2016-05-24
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多