5

I have a list of 150 variables that have the following possible values:

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

I want to convert these to be used as color for a matplot scatter plot. Currently I wrote a function to manually map from my data domain to a color range, something like:

  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)

This works, however, I must specify the color individual colors that each element of my domain gets mapped to. Is there a way to have matplotlib to this for me, so I can take advantage of cmaps? D3 has a way of mapping from a data domain to color range.

4

2 回答 2

3

您可以从 导入颜色图matplotlib.cm,然后通过将其作为函数调用来从中选择单个颜色。它接受从 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))
于 2015-10-20T20:32:45.667 回答
2

这是@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)
于 2018-03-22T21:03:22.320 回答