python - 在 matplotlib 图中使用多种颜色

标签 python colors matplotlib plot

我有一个二维数据点 (x,y) 的 numpy 数组,它们分为三类 (0,1,2)。

a = array([[ 1, 2, 3, 4, 5, 6, 7, 8 ],
           [ 9, 8, 7, 6, 5, 4, 3, 2 ]])

class = array([0, 2, 1, 1, 1, 2, 0, 0])

我的问题是我是否可以用多种颜色绘制这些点。我想做这样的事情:

colors = list()
for i in class:
    if i == 0:
        colors.append('r')
    elif i == 1:
        colors.append('g')
    else:
        colors.append('b')

print colors
['r', 'b', 'g', 'g', 'g', 'b', 'r', 'r']

pp.plot(a[0], a[1], color = colors)

最佳答案

我假设您想绘制不同的点。在这种情况下, 如果你定义一个 numpy 数组:

colormap = np.array(['r', 'g', 'b'])

然后您可以使用 colormap[categories] 生成颜色数组:

In [18]: colormap[categories]
Out[18]: 
array(['r', 'b', 'g', 'g', 'g', 'b', 'r', 'r'], 
      dtype='|S1')

import matplotlib.pyplot as plt
import numpy as np

a = np.array([[ 1, 2, 3, 4, 5, 6, 7, 8 ],
              [ 9, 8, 7, 6, 5, 4, 3, 2 ]])

categories = np.array([0, 2, 1, 1, 1, 2, 0, 0])

colormap = np.array(['r', 'g', 'b'])

plt.scatter(a[0], a[1], s=50, c=colormap[categories])
plt.show()

产量

enter image description here

关于python - 在 matplotlib 图中使用多种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15678373/

相关文章:

css - 需要在选择表格行时创建背景颜色

java - 是否可以为 javafx textField/Area 中的不同行设置不同的颜色?

python - 在 matplotlib imshow 中调整网格线和刻度线

python - 使用 Matplotlib v2.2.2 的烛台图表?

python - 额外的 python 库无法在 macOS 上运行

python - 优化策略使用(数据生成)

Python - 通过模块属性(按字符串名称)访问类实例

python正则表达式,空格之间只有数字

winapi - 设置 Windows 控制台的文本颜色未按预期工作

python - 如何使用 Seaborn 在同一图上绘制多个直方图