【问题标题】:Scatter plot with colors and legends [duplicate]带有颜色和图例的散点图[重复]
【发布时间】:2018-03-15 22:40:55
【问题描述】:

我很难创建一个散点图,以不同颜色显示不同类的点以及图例中类的相应标签。

我有 52 个样本、2 个特征和 3 个类(1,2 和 3 类)。数据在X数组中,标签在labels数组中。

我想绘制将包含相应颜色的类名(1,2 和 3)的图例。


我的代码

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(52,2)

labels = np.ones(x.shape[0])
labels[0:8] = 1
labels[8:31] = 2 
labels[31:] = 3

plt.scatter(x[:,0], x[:,1], c = labels, label = labels)
plt.legend()
plt.show()

结果

【问题讨论】:

    标签: python matplotlib scatter-plot


    【解决方案1】:

    一种方法是分别绘制你的类:

    x = np.random.rand(52,2)
    
    labels = np.ones(x.shape[0])
    labels[0:8] = 1
    labels[8:31] = 2 
    labels[31:] = 3
    
    
    for i in np.unique(labels):
        plt.scatter(x[np.where(labels==i),0], x[np.where(labels==i),1], label=i)
    plt.legend()
    plt.show()
    

    【讨论】:

    • 你好。我带着一个新问题回来了。我可以这样做,但这次使用 seaborn 的 sns.jointplot 函数?
    【解决方案2】:

    取自:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html

    3.显式定义图例中的元素

    要完全控制哪些艺术家有图例条目,可以 传递一个可迭代的传奇艺术家,然后是一个可迭代的 图例标签分别:

    legend((line1, line2, line3), ('label1', 'label2', 'label3'))
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多