【问题标题】:How to display and legend two types of color in ax.scatter?如何在 ax.scatter 中显示和图例两种颜色?
【发布时间】:2021-08-11 22:05:46
【问题描述】:

我想根据标签的不同显示两种颜色。具体来说,当 label = 2 时,点颜色为黑色,其余点遵循 cmap ='Dark2'。我只有一个简单的想法,将点(label = 2)再次重叠,这样的代码,

import matplotlib.pyplot as plt
from sklearn import datasets
from collections import Counter
iris = datasets.load_iris()
X = iris.data
y = iris.target
df = pd.DataFrame(X, columns = iris.feature_names)
fig, ax = plt.subplots(figsize=(12,8))
points = ax.scatter(df.values[:,0], 
    df.values[:,1],
    c = y,
    cmap='Dark2')  #others is follow this cmap

for i in range (len(y)):
    if y[i] == 2:
        ax.scatter(df.values[i,0],df.values[i,1], c = 'k') #when label = 2,points color is black 

handles, _ = points.legend_elements()
labels =sorted([f'{item}: {count}' for item, count in Counter(y).items()])
ax.legend(handles, labels, loc = "lower right",title = 'clusters')  

plt.show()

现在,问题是黑点的颜色仍然遵循以前的颜色图,比如(是灰色而不是黑色)。如何解决这个问题呢?

【问题讨论】:

  • 现在的问题是它显示错误“c”参数有 555 个元素,这对于使用大小为 555 的“x”、大小为 555 的“y”是不可接受的。在“cmap”行中= 'Dark2' 当我在我的实际代码中更正时,我确定它在数据集中是否太长,因此它无法将标签识别为颜色

标签: python python-3.x matplotlib


【解决方案1】:

可能有更优雅的解决方案,但您可以手动向图例添加一个标记:

import pandas as pd
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
from sklearn import datasets
from collections import Counter
iris = datasets.load_iris()

X = iris.data
y = iris.target
df = pd.DataFrame(X, columns = iris.feature_names)

fig, ax = plt.subplots(figsize=(12,8))

df1 = df[y!= 2] 
points = ax.scatter(df1.values[:,0], df1.values[:,1], marker = 'o', c = y[y!=2], cmap='Dark2') 

df2 = df[y== 2] 
points2 = ax.scatter(df2.values[:,0], df2.values[:,1], marker = 'o', color = 'k')

handles, _ = points.legend_elements()
labels = sorted([f'{item}: {count}' for item, count in Counter(y).items()])

one_more = mlines.Line2D([], [], color='k', marker='o', linestyle='None', markersize = handles[0].get_ms())
ax.legend(handles + [one_more], labels, loc = "lower right",title = 'clusters')  
plt.show()

它给出:

【讨论】:

  • 谢谢,但是我的实际代码在 cmap 行中显示了一些错误,它显示:'c' 参数有 555 个元素,这不能与大小为 555、'y' 的 'x' 一起使用尺寸为 555。我只能更改图例的代码部分吗?我的意思是重叠图例中的颜色?
  • @4daJKong 如果你想对你的代码做最少的修改,那么你可以:1)添加到你的代码import matplotlib.lines as mlines,2)在你定义handles之后添加我的行在代码中定义 one_more, 3) 的代码将 ax.legend(handles, ...) 行替换为 ax.legend(handles[:-1] + [one_more], ...) 。应该这样做。
  • 非常感谢!但是现在这里只有一个问题,如果我在scatter3D中应用它,有一些点不能与前一个重叠,即使我设置了大尺寸的黑点..如何解决它......
  • @4daJKong 您真的不应该将这些重叠点绘制两次。您应该分别用y != 2y == 2 分别绘制点。这是我在回答中建议的,这也是@aminrd 在他的回答中所做的。
【解决方案2】:

您可以首先在 y != 2 的记录上绘制散点图,然后在 y == 2 上绘制散点图,但是这一次,因为您想要所有这些 Black 而不是使用 c,因此您设置了 color='black'这些数据点没有不同的值。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from collections import Counter

iris = datasets.load_iris()
X = iris.data
y = iris.target
df = pd.DataFrame(X, columns=iris.feature_names)
fig, ax = plt.subplots(figsize=(12, 8))

points = ax.scatter(df.values[np.where(y != 2), 0],
           df.values[np.where(y != 2), 1],
           c=y[np.where(y != 2)], cmap='Dark2')

p2 = ax.scatter(df.values[np.where(y == 2), 0], df.values[np.where(y == 2), 1], color='black')

handles, _ = points.legend_elements()
labels =sorted([f'{item}: {count}' for item, count in Counter(y[np.where( y != 2)]).items()])
ax.legend([*handles, p2], [*labels, f'2: {np.sum(y == 2)}'], loc="lower right",title='clusters')

plt.show()

输出:

【讨论】:

  • 感谢您的回复,但请看右下角,我觉得这里有些问题
  • @4daJKong 错误已修复
  • 再次感谢您,但我的实际代码显示错误:'c' 参数有 555 个元素,这对于大小为 555 的 'x'、大小为 555 的 'y' 是不可接受的。在“cmap='Dark2'”这行你知道为什么吗?
  • 只能更改图例的代码部分吗?我的意思是重叠图例中的颜色?
猜你喜欢
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多