【问题标题】:Seaborn heatmap, custom tick valuesSeaborn 热图,自定义刻度值
【发布时间】:2018-05-26 19:45:04
【问题描述】:

我将 pandas 数据框绘制到 seaborn 热图,我想为特定位置设置特定的 y 轴刻度。

我的数据框索引是 100 行,对应于“深度”参数,但该索引中的值没有按很好的间隔排列: 我想将刻度标签设置为 100 的倍数。我可以使用:

yticks = np.linspace(10,100,10)
ylabels = np.linspace(100,1000,10)

对于我的数据框,它有 100 行,值从大约 100 到 1000,但结果显然是不可取的,因为刻度标签的位置显然不对应于正确的深度值(索引 value),仅在索引中的位置。

我怎样才能生成一个热图,其中的情节是扭曲的,以便实际深度值(索引 )与我设置的 ylabels 对齐?

一个复杂的因素也是索引值不是线性采样的......

【问题讨论】:

  • 是否可以对数据与深度进行拟合或插值以获得均匀深度标记处的值?这似乎是要走的路。
  • 首先,提供问题的minimal reproducible example,以便可以重现它。其次明确说明所需的输出是什么。如果采样不是线性的,那么简单地在轴上设置一些值当然会给出错误的标签。那么你打算如何标记情节呢?

标签: python pandas matplotlib seaborn


【解决方案1】:

使用 seaborn 绘图时,您必须为 heatmap 函数指定参数 xticklabelsyticklabels。在您的情况下,这些参数必须是带有自定义刻度标签的列表。

【讨论】:

    【解决方案2】:

    我的解决方案有点难看,但对我有用。假设您的深度数据在depth_list 中,num_ticks 是您想要的刻度数:

    num_ticks = 10
    # the index of the position of yticks
    yticks = np.linspace(0, len(depth_list) - 1, num_ticks, dtype=np.int)
    # the content of labels of these yticks
    yticklabels = [depth_list[idx] for idx in yticks]
    

    然后以这种方式绘制热图(您的数据在data 中):

    ax = sns.heatmap(data, yticklabels=yticklabels)
    ax.set_yticks(yticks)
    plt.show()
    

    【讨论】:

      【解决方案3】:

      我已经开发了一个解决方案,它符合我的意图,在 liwt31 的解决方案之后进行了修改:

      def round(n, k):
          # function to round number 'n' up/down to nearest 'k'
          # use positive k to round up
          # use negative k to round down
      
          return n - n % k
      
      # note: the df.index is a series of elevation values
      tick_step = 25 
      tick_min = int(round(data.index.min(), (-1 * tick_step)))  # round down
      tick_max = (int(round(data.index.max(), (1 * tick_step)))) + tick_step  # round up
      
      # the depth values for the tick labels 
      # I want my y tick labels to refer to these elevations, 
      # but with min and max values being a multiple of 25.
      yticklabels = range(tick_min, tick_max, tick_step)
      # the index position of the tick labels
      yticks = []
      for label in yticklabels:
          idx_pos = df.index.get_loc(label)
          yticks.append(idx_pos)
      
      cmap = sns.color_palette("coolwarm", 128)
      plt.figure(figsize=(30, 10))
      ax1 = sns.heatmap(df, annot=False, cmap=cmap, yticklabels=yticklabels)
      ax1.set_yticks(yticks)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-05
        • 2020-04-19
        • 2016-01-14
        • 2016-03-29
        • 2021-05-08
        • 2020-10-21
        • 2021-04-17
        相关资源
        最近更新 更多