【问题标题】:How to plot an array as a heatmap timeseries如何将数组绘制为热图时间序列
【发布时间】:2019-10-23 16:04:41
【问题描述】:

我正在尝试创建一个 sns 热图,其中每一行代表一个数组条目。 我的数组看起来像:

arr = [[a, b, c], [b, c, d], [e, f, g]]

我有一个颜色字典,它为每个条目分配一种颜色。我使用这两个数组创建了另一个数组,以便它包含要绘制的颜色顺序(即:

col = [[c0, c1, c2], [c1, c2, c3], [c4, c5, c6]]

其中 c0,1.. 都是十六进制颜色代码。有没有办法把它变成热图?

【问题讨论】:

    标签: python pandas time-series seaborn heatmap


    【解决方案1】:

    col 已经一张热图。不幸的是,matplotlib 无法直接将十六进制颜色绘制为图像,因此您需要先转换为 rgb。

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    
    
    col = [["#" + "".join(np.random.choice(list("0123456789abcdef"),6))
                    for _ in range(4)] for _ in range(4)]
    
    
    col = np.array(col)
    img = mcolors.to_rgba_array(col.flatten()).reshape(*col.shape, 4)
    
    plt.imshow(img)
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      cmap 参数完成这项工作。 (doc)。您可以使用color_palettes 方法(doc) 定义自己的调色板

      在这里,我将0 作为颜色列表的第一个元素,1 作为颜色列表的第二个元素,依此类推。

      代码如下:

      # import modules
      import seaborn as sns
      import matplotlib.pyplot as plt
      
      #Init seaborn
      sns.set()
      
      # Your data as decimal array
      col = [[0, 1, 2], [1, 2, 3], [4, 5, 6]]
      
      # Your custum color palette
      flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71",  "#30095e"]
      
      # Draw heatmap with the custom palette color
      ax = sns.heatmap(col, cmap=sns.color_palette(flatui))
      
      # Show graph
      plt.show()
      

      【讨论】:

      • 谢谢!这适用于一个小样本,但是一旦我使用更大的数据集,我就会有这个:IndexError: Inconsistent shape between the condition and the input (got (25, 1) and (25,)) 即使列表格式相同跨度>
      • 抱歉耽搁了。仅凭这一点很难知道。哪条线出现错误?你有重现错误的例子吗?
      猜你喜欢
      • 2020-03-29
      • 2020-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多