【问题标题】:Auto adjust font size in seaborn heatmap在 seaborn 热图中自动调整字体大小
【发布时间】:2015-10-13 13:43:44
【问题描述】:

使用 seaborn 热图时,有没有办法自动调整字体大小以使其完全适合正方形? 例如在:

sns.heatmap(corrmat, vmin=corrmat.values.min(), vmax=1, square=True, cmap="YlGnBu", 
        linewidths=0.1, annot=True, annot_kws={"size":8})  

这里的大小在“annot_kws”中设置。

【问题讨论】:

  • 没有;它依赖于太多的事情来可靠地预测。
  • 感谢annot_kws={"size": 8}!正是我想要的:)。

标签: python matplotlib seaborn


【解决方案1】:

你也可以这样做:

sns.heatmap(corrmat, vmin=corrmat.values.min(), vmax=1, square=True, cmap="YlGnBu", linewidths=0.1, annot=True, annot_kws={"fontsize":8})  

【讨论】:

    【解决方案2】:

    如果你想要一些自动化的东西,这还不错:

    annot_kws={"size": 35 / np.sqrt(len(corrmat))},
    

    【讨论】:

      【解决方案3】:

      调整seaborn heatmap的字体大小,有不同的方法

      import seaborn as sns # for data visualization
      flight = sns.load_dataset('flights') # load flights datset from GitHub seaborn repository
      
      # reshape flights dataeset in proper format to create seaborn heatmap
      flights_df = flight.pivot('month', 'year', 'passengers') 
      
      sns.heatmap(flights_df) # create seaborn heatmap
      
      sns.set(font_scale=2) # font size 2
      

      输出 >>>

      sns.set(font_scale=2) # font size 2 为所有 seaborn 图形标签设置大小 如果您愿意,可以采用另一种方法

      import seaborn as sns # for data visualization
      import matplotlib.pyplot as plt # for data visualization
      
      flight = sns.load_dataset('flights') # load flights datset from GitHub seaborn repository
      
      # reshape flights dataeset in proper format to create seaborn heatmap
      flights_df = flight.pivot('month', 'year', 'passengers') 
      
      sns.heatmap(flights_df) # create seaborn heatmap
      
      
      plt.title('Heatmap of Flighr Dataset', fontsize = 20) # title with fontsize 20
      plt.xlabel('Years', fontsize = 15) # x-axis label with fontsize 15
      plt.ylabel('Monthes', fontsize = 15) # y-axis label with fontsize 15
      
      plt.show()
      

      输出 >>>

      【讨论】:

        【解决方案4】:

        虽然它会扭曲热图,但此示例说明了如何使用 .set(...) 上下文缩放字体

        import matplotlib.pyplot as plt
        import seaborn as sns
        sns.set(font_scale=3)
        
        # Load the example flights dataset and conver to long-form
        flights_long = sns.load_dataset("flights")
        flights = flights_long.pivot("month", "year", "passengers")
        
        # Draw a heatmap with the numeric values in each cell
        f, ax = plt.subplots(figsize=(9, 6))
        sns.heatmap(flights, annot=True, fmt="d", linewidths=.5, ax=ax)
        f.savefig("output.png")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-02
          • 1970-01-01
          • 1970-01-01
          • 2017-03-26
          • 1970-01-01
          • 2021-11-24
          • 2011-02-28
          • 2011-02-07
          相关资源
          最近更新 更多