【问题标题】:Convert categorical variable to color with Matplotlib使用 Matplotlib 将分类变量转换为颜色
【发布时间】:2015-10-20 20:17:43
【问题描述】:

我有一个包含以下可能值的 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 有一种从数据域映射到颜色范围的方法。

【问题讨论】:

    标签: python matplotlib mpld3


    【解决方案1】:

    您可以从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))
    

    【讨论】:

    • 我不得不根据我的具体情况进行一些更改,但是,cool(float(i)/n) 完全按照我的需要工作。谢谢。
    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 2016-12-16
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      相关资源
      最近更新 更多