【问题标题】:How to add a legend to matplotlib scatter plot如何在 matplotlib 散点图中添加图例
【发布时间】:2017-10-14 05:04:00
【问题描述】:

我正在尝试绘制 PCA,其中一种颜色是标签 1,另一种颜色应该是标签 2。当我想添加带有 ax1.legend() 的图例时,我只会得到蓝点的标签或没有标签一点也不。如何为蓝色和紫色点添加带有正确标签的图例?

sns.set(style = 'darkgrid')

fig, ax1 = sns.plt.subplots()  

x1, x2 = X_bar[:,0], X_bar[:,1] 
ax1.scatter(x1, x2, 100, edgecolors='none', c = colors)
fig.set_figheight(8)
fig.set_figwidth(15)

【问题讨论】:

  • 不,我没有。我想这就是问题所在。所有信息都在 x1 和 x2 中,并且已经使用第一个 ax1.scatter() 绘制。
  • 当我尝试得到 TypeError: 'PathCollection' object is not iterable
  • 给我同样的问题,TypeError: 'PathCollection' object is not iterable
  • pca.fit(X[:50]) X_bar = pca.transform(X[:50])。颜色只是对应标签的蓝色和紫色列表(25 蓝色,25 紫色)。这种方式可能是多余的,但这样标签是正确的。
  • same TypeError :(

标签: python matplotlib plot legend seaborn


【解决方案1】:

看起来您正在绘制在两种颜色之间振荡的每个点。根据这个问题的答案subsampling every nth entry in a numpy array 您可以使用 numpys 数组切片来绘制两个单独的数组,然后照常进行图例。 对于一些示例数据:

import numpy as np
import numpy.random as nprnd
import matplotlib.pyplot as plt

A = nprnd.randint(1000, size=100)
A.shape = (50,2)

x1, x2 = np.sort(A[:,0], axis=0), np.sort(A[:,1], axis=0)

x1
Out[50]: 
array([ 46,  63,  84,  96, 118, 127, 137, 142, 181, 187, 187, 207, 210,
       238, 238, 330, 334, 335, 346, 346, 350, 392, 400, 426, 467, 531,
       550, 567, 569, 572, 583, 625, 637, 661, 671, 677, 698, 713, 777,
       796, 837, 850, 866, 868, 874, 890, 919, 972, 992, 993])
x2
Out[51]: 
array([  2,  44,  49,  51,  72,  84,  86, 118, 120, 133, 150, 155, 156,
       159, 199, 202, 250, 281, 289, 317, 317, 386, 405, 414, 427, 461,
       507, 510, 543, 552, 553, 555, 559, 576, 618, 622, 633, 647, 665,
       672, 682, 685, 745, 767, 776, 802, 808, 813, 847, 973])


labels=['blue','red']

fig, ax1 = plt.subplots()
ax1.scatter(x1[0::2], x2[0::2], 100, edgecolors='none', c='red', label = 'red')
ax1.scatter(x1[1::2], x2[1::2], 100, edgecolors='none', c='black', label = 'black')

plt.legend()
plt.show()

对于您的代码,您可以这样做:

sns.set(style = 'darkgrid')
fig, ax1 = sns.plt.subplots()  

x1, x2 = X_bar[:,0], X_bar[:,1] 
ax1.scatter(x1[0::2], x2[0::2], 100, edgecolors='none', c = colors[0], label='one')
ax1.scatter(x1[1::2], x2[1::2], 100, edgecolors='none', c = colors[1], label='two')
fig.set_figheight(8)
fig.set_figwidth(15)
plt.legend()

【讨论】:

    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    相关资源
    最近更新 更多