【问题标题】:How can I create a legend for my scatter plot which matches the colours used in the plot?如何为散点图创建与图中使用的颜色匹配的图例?
【发布时间】:2022-06-11 18:53:41
【问题描述】:

我使用matplotlib.pyplot 创建了一个散点图(实际上是两个相似的子图),我将其用于样式文本分析。我用来制作情节的代码如下:

import matplotlib.pyplot as plt
import numpy as np

clusters = 4
two_d_matrix = np.array([[0.00617068, -0.53451777], [-0.01837677, -0.47131886], ...])
my_labels = [0, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

fig, (plot1, plot2) = plt.subplots(1, 2, sharex=False, sharey=False, figsize=(20, 10))

plot1.axhline(0, color='#afafaf')
plot1.axvline(0, color='#afafaf')
for i in range(clusters):
    try:
        plot1.scatter(two_d_matrix[i:, 0], two_d_matrix[i:, 1], s=30, c=my_labels, cmap='viridis')
    except (KeyError, ValueError) as e:
        pass
plot1.legend(my_labels)
plot1.set_title("My First Plot")

plot2.axhline(0, color='#afafaf')
plot2.axvline(0, color='#afafaf')
for i in range(clusters):
    try:
        plot2.scatter(two_d_matrix[i:, 0], two_d_matrix[i:, 1], s=30, c=my_labels, cmap='viridis')
    except (KeyError, ValueError) as e:
        pass
plot2.legend(my_labels)
plot2.set_title("My Second Plot")

plt.show()

因为my_labels 中有四个不同的值,所以图中出现了四种颜色,这些应该对应于我期望找到的四个集群。

问题是图例只有三个值,对应my_labels中的前三个值。似乎图例并未显示每种颜色的键,而是显示每个轴,然后显示其中一种颜色。这意味着图中出现的颜色与图例中出现的颜色不匹配,因此图例不准确。我不知道为什么会这样。

理想情况下,图例应为my_labels 中的每个唯一值显示一种颜色,因此应如下所示:

如何让图例准确显示它应该显示的所有值,即图中出现的每种颜色对应一个值?

【问题讨论】:

  • @medium-dimensional 我在上传之前对其进行了测试,它对我有用。它给出了什么错误?我在这里的代码中唯一无法提供的是完整的 two_d_matrix 数组,因为它太长了。

标签: matplotlib colors legend scatter-plot


【解决方案1】:

在调用plot1.legend 或plot2.legend 之前,您可以将label = None 传递给plot1.axhline 或axvline(类似于plot2.axhline 或plot2.axvline。)这将确保它不会干扰绘制散点图例,也不标记这些线。

要获取所有散点类别的标签,您必须调用plot1.scatter 或plot2.scatter,方法是传递标签并仅从two_d_matrix 中选择其索引与my_labels 中标签索引匹配的值.

你可以这样做:

import matplotlib.pyplot as plt
import numpy as np

# Generate some (pseudo) random which is reproducible
generator = np.random.default_rng(seed=121)
matrix = generator.uniform(size=(40, 2))
matrix = np.sort(matrix)

clusters = 4
my_labels = np.array([0, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3])

fig, ax = plt.subplots(1, 1)

# Select data points wisely
for i in range(clusters):
    pos = np.where(my_labels == i)
    ax.scatter(matrix[pos, 0], matrix[pos, 1], s=30, cmap='viridis', label=i)  

ax.legend()
ax.set_title("Expected output")
plt.show()

这给出了:


当前输出与预期输出对比:

上图的代码:

import matplotlib.pyplot as plt
import numpy as np

# Generate some (pseudo) random which is reproducible
generator = np.random.default_rng(seed=121)
matrix = generator.uniform(size=(40, 2))
matrix = np.sort(matrix)

clusters = 4
my_labels = np.array([0, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3])

fig, ax = plt.subplots(1, 2)

# Question plot
for i in range(clusters):
    ax[0].scatter(matrix[i:, 0], matrix[i:, 1], s=30, cmap='viridis', label=i)  

ax[0].axhline(0, color='#afafaf', label=None)
ax[0].axvline(0, color='#afafaf', label=None)


# Answer plot
for i in range(clusters):
    pos = np.where(my_labels == i) # <- choose index of data points based on label position in my_labels
    ax[1].scatter(matrix[pos, 0], matrix[pos, 1], s=30, cmap='viridis', label=i)  

ax[1].axhline(0, color='#afafaf', label=None)
ax[1].axvline(0, color='#afafaf', label=None)

ax[0].legend()
ax[0].set_title("Current output (with label = None)")

ax[1].legend()
ax[1].set_title("Expected output")

plt.show()

【讨论】:

    猜你喜欢
    • 2018-08-24
    • 2021-06-13
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2021-10-29
    相关资源
    最近更新 更多