通常我们在使用matplotlib.pyplot库中的plot函数或者scatter函数画散点图时,会使用不同的颜色标记不同点,尤其在聚类中会使用不同颜色标记不同类簇,但是现有的颜色名字很少,例如{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}。如果类簇数很少的话,可以直接用这几个进行表示,但是如果类簇数比较多,超过10个的,就不好采用上面的方法,当然也可以采用和marker参数进行结合例如‘b*’,'bo'.
假如我们只想用颜色来区分,如何生成更多的颜色名。
下面介绍一种方法,引入库函数 colormap.rgb2hex, 如果colormap库不存在,需要提前安装。下面是完整代码
from colormap import rgb2hex
import numpy as np
from matplotlib import pyplot as plt
color_names = []
sample = [0, 0.25, 0.5, 0.75, 1] # 此处可根据自己情况进行设置
for i in sample:
for j in sample:
for k in sample:
col = rgb2hex(i, j, k, normalised=True)
color_names.append(col)
print(color_names[0])
x = np.random.random((1000, 1))
j = 0
for i in range(len(color_names)):
y = j*3 + np.random.random((1000, 1)) * 2
j += 1
plt.scatter(x, y, color=color_names[i])
plt.show()
最终将color的名字保存在color_names中,例如:#000000
colormap的图如下:
最后可从color_names中获取color的名字来对plot函数中的color参数进行设置,下面是一个效果图
附一个画聚类结果的函数代码
# coding:utf-8
from colormap import rgb2hex
from matplotlib import pyplot as plt
import numpy as np
colors = []
sample = [0, 0.25, 0.5, 0.75, 1]
for i in sample:
for j in sample:
for k in sample:
col = rgb2hex(i, j, k, normalised=True)
colors.append(col)
def plot_result(filename, x, ncluster, cl, icl):
"""
params
--------
filename: 数据集名
x: 二维数据集np.ndarray格式
ncluster: 类簇数
cl: 聚类结果标签
icl: 类簇中心
"""
# 画出聚类结果,每一类用一种颜色
x_max = x[:, 0].max()
x_min = x[:, 0].min()
y_max = x[:, 1].max()
y_min = x[:, 1].min()
m = -1
for i in range(ncluster):
index = np.nonzero(cl == i)[0]
x0 = x[index, 0]
x1 = x[index, 1]
cn = round(len(colors) * i / ncluster)
for j in range(len(x0)):
plt.plot(x0[j], x1[j], marker='o', markersize=5, color=colors[cn])
for c in range(ncluster):
plt.plot(x[icl[c]][0], x[icl[c]][1], marker='s', markerfacecolor='g', markeredgecolor='r', markersize=8)
plt.title("the result of cluster on {}".format(filename))
plt.axis([x_min-.05, x_max+.05, y_min-.05, y_max+.05])
plt.show()