【问题标题】:Plot data point according to their class labels in Python根据 Python 中的类标签绘制数据点
【发布时间】:2014-09-08 14:53:58
【问题描述】:

我正在尝试绘制颜色与其类标签相对应的数据点。在数据可视化方面,我更熟悉 R。在 R 中,我会执行以下操作:

x = matrix(runif(100), 2, 20)
y = matrix(runif(100), 2, 20)
labels = c(rep(0, 20), rep(1, 20))
plot(rbind(x, y), col = labels)

然后我将能够得到来自两个类的数据点的散点图,它们的点颜色是标签。我不确定如何在 python 中执行此操作。到目前为止,我所做的是

import numpy
plot(numpy.vstack((x,y)), c = labels) 

但显然 python 不喜欢颜色的整数值....您的帮助将不胜感激!

【问题讨论】:

  • 使用 numpymatplotlib 库。这应该会让你朝着正确的方向前进。

标签: python r plot


【解决方案1】:

你在正确的轨道上。您有三个数据向量:xyc,其中c 是一个带有类标签的整数数组。

您可以做的最简单的事情是:

import matplotlib.pyplot as plt
import numpy as np

# create some random data grouped into three groups
x = np.random.random(100)
y = np.random.random(100)
c = np.random.choice(range(3), 100)

# plot the data
fig = plt.figure()
ax = fig.add_subplot(111)
# plot x,y data with c as the color vector, set the line width of the markers to 0
ax.scatter(x, y, c=c, lw=0)

这给了你:

如果您想更好地控制颜色,您甚至可以创建自己的颜色表,例如:

mycolors = np.array([ 'g', 'm', 'c' ])
ax.scatter(x, y, c=mycolors[c], lw=0)

现在颜色是 0=绿色、1=洋红色、2=青色:

当然,您也可以指定颜色三元组 (RGB) 或四元组 (RGBA) 来代替颜色名称。这为您提供了更精细的控制。

您也可以使用内置颜色图或创建自己的颜色图。我只是发现上面的解决方案是最透明的,离散数据只有很少的可能值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2018-01-22
    • 1970-01-01
    • 2023-02-07
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多