【问题标题】:Map discrete value to color by type and position按类型和位置将离散值映射到颜色
【发布时间】:2015-06-05 06:55:06
【问题描述】:

我昨天问了如何将离散值映射到颜色,得到了以下有用的答案。

Map discrete value to color

我正在尝试根据 4 个离散值 1、2、3、4 绘制颜色。我想将 1 定义为黑色,2 定义为红色,3 定义为黄色,4 定义为绿色。有人知道怎么做吗?

您可以改用imshow,并使用dict 来映射您想要的颜色:

colordict = {1:(0,0,0),2:(1,0,0),3:(1,1,0),4:(0,1,0)}
test = ([1,2,2,1,3],[1,1,1,1,4],[2,1,1,2,1])
test_rgb = [[colordict[i] for i in row] for row in test]
plt.imshow(test_rgb, interpolation = 'none')

但是,值列表有一些数据属性,我也想在图表中显示它们。具体有两点:

  1. 每个颜色列表都有一个唯一的类型,因此图表应该显示每个水平颜色条的类型。

  2. 每个颜色列表都有一个对应的位置列表,表示从最后一个开始的结束位置(都是从0开始到20结束)

dict = {'Type': ['A', 'B','C'], 'ColorList': [[1,2,2,1,3],[1,1,1,1,4],[2,1,1,2]], 'Position': [[3,6,9,15,20], [2,10,13,16,20], [6, 10, 12, 20]]}

df = pd.DataFrame(dict)

所以,除了 x 和 y 轴更改以指示颜色的位置和颜色列表的类型之外,图表应该看起来相似。

非常感谢任何帮助

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您需要plt.annotate 函数;例如,对于第一个方块plt.annotate ('black', xy = (0, 0), color = 'white')

    关于其余代码,最好使用enum 的子类(需要 Python 3.0):

    >>> from enum import Enum
    >>> class Color(Enum):
    ...     black = 1
    ...     red = 1
    ...     yellow = 2
    ...     green = 3
    

    可能包括以下内容:

    ...     def RGB (self):
    ...         return {1:(0, 0, 0), 2:(1, 0, 0), 3:(1, 1, 0), 4:(0, 1, 0)}[self.value]
    

    使用Enum 的子类和列表推导进行重写应该使您的代码更易于使用。

    PS:我认为你用dict = ... 覆盖了标准函数dict

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多