使用 Matplotlib 将分类变量转换为颜色

Convert categorical variable to color with Matplotlib

我有一个包含 150 个变量的列表,这些变量具有以下可能的值:

   domain = ['val1', 'val2', 'val2'] 

我想将它们转换为 matplot 散点图的颜色。目前我写了一个函数来手动从我的数据域映射到颜色范围,比如:

  colors = ['aquamarine','purple','blue']
  color_map = dict(zip(domain, colors)) 
  colorize = lambda x : color_map[x]
  c = list(map(colorize, labels))

  #and then I explicitly pass the array to scatter: 
  scatter = ax.scatter(t_x,
                 t_y,
                 c=c,
                 alpha=0.3,
                 cmap=plt.cm.cool,
                 s = 500)

这可行,但是,我必须指定域中每个元素映射到的颜色。有没有办法让我使用 matplotlib,这样我就可以利用 cmaps? D3 有一种从数据域映射到颜色范围的方法。

您可以从 matplotlib.cm 导入颜色图,然后通过将其作为函数调用来从中导入 select 各种颜色。它接受从 0 到 1(或从 1 到 255,这有点奇怪)的输入数字,并沿着颜色图为您提供颜色。

import matplotlib
from matplotlib.cm import cool

def get_n_colors(n):
    return[ cool(float(i)/n) for i in range(n) ]

然后您可以为分类变量生成颜色:

colors = get_n_colors(len(domain))

这是@C_Z_答案的改编版本,更容易用于绘图:

# x, y, and category_values should all be the same length (the # of data points)

import matplotlib.pyplot as plt
from matplotlib.cm import viridis

num_categories = len(set(category_values))

colors = [viridis(float(i)/num_categories) for i in category_values]
plt.scatter(x, y, color=colors)