【问题标题】:How can I set x_ticks for a heatmap in Seaborn?如何在 Seaborn 中为热图设置 x_ticks?
【发布时间】:2021-01-30 15:54:43
【问题描述】:

我想从[0.01, 0.02, ......1.01] 更改x_ticks 到[0.1,0.2,...,1.0]

import matplotlib.pyplot as plt
import numpy as np 
import pandas as pd
import seaborn as sns

colums = np.arange(0.01, 1.01, 0.01)
df = pd.DataFrame(np.random.randint(0, 100, size=(100, 100)), columns=colums.tolist())
ax1 = sns.heatmap(df, vmin=0., vmax=1, linewidths=.05, cbar_kws={'label': '?'})
plt.show()

我尝试通过ax1.set_xticks([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) 调整刻度,但没有成功。

【问题讨论】:

    标签: python-3.x matplotlib seaborn


    【解决方案1】:

    在内部,刻度位置是分类0, 1, 2, ...。因此,您可以调用ax1.set_ticks([9, 19, 29, ...]) 来获取名为0.1, 0.2, 0.3, ... 的列的刻度。然后调用ax1.set_ticklabels(...)设置想要的字符串:

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    df = pd.DataFrame(np.random.randint(0, 100, size=(100, 100)))
    ax1 = sns.heatmap(df, vmin=0., vmax=1, linewidths=.05, cbar_kws={'label': '?'})
    # ax1.set_xticks(range(4, 100, 5))
    # ax1.set_xticklabels(f'{c:.2f}' for c in np.arange(0.05, 1.01, 0.05))
    ax1.set_xticks(range(9, 100, 10))
    ax1.set_xticklabels(f'{c:.1f}' for c in np.arange(0.1, 1.01, 0.1))
    plt.show()
    

    PS:如果您希望列具有好听的名称(默认它们只是0,1,2,...),您可以将数据框创建为pd.DataFrame(..., columns=[f'{c:.2f}' for c in np.arange(0.01, 1.01, 0.01)])。这样,列名将是具有所需精度的字符串。如果您只使用数字而不是字符串,pandas 会将这些转换为字符串(通过str())而不知道需要多少位数字。不可避免的舍入错误可能会创建不需要的字符串,例如 0.21000000000000002

    【讨论】:

      【解决方案2】:

      我的解决方案有点难看,但对我有用。

      import matplotlib.pyplot as plt
      import numpy as np 
      import pandas as pd
      import seaborn as sns
      
      colums = np.arange(0.01, 1.01, 0.01)
      df = pd.DataFrame(np.random.randint(0, 100, size=(100, 100)), columns=colums.tolist())
      
      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(df.index.min(), (-1 * tick_step)))  # round down
      tick_max = (int(round(df.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.
      xticklabels = range(tick_min, tick_max, tick_step)
      # the index position of the tick labels
      xticks = []
      for label in xticklabels:
          idx_pos = df.index.get_loc(label)
          xticks.append(idx_pos)
      
      cmap = sns.color_palette("coolwarm", 128)
      plt.figure(figsize=(12, 10))
      ax1 = sns.heatmap(df, annot=False, cmap=cmap, xticklabels=xticklabels)
      ax1.set_xticks(xticks)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2019-03-22
        • 2016-02-17
        • 1970-01-01
        • 2022-06-13
        • 2021-01-01
        • 2020-04-10
        • 1970-01-01
        • 2016-02-20
        • 2017-07-19
        相关资源
        最近更新 更多