Overlapping yticklabels: Is it possible to control cell size of heatmap in seaborn?

后端 未结 1 1697
滥情空心
滥情空心 2020-12-06 07:37

I have a dataset with around 200 observations which I would like to plot as a heatmap. Each observation has a string associated with it which I would like to display. My pro

相关标签:
1条回答
  • 2020-12-06 08:15

    The only way to make more room for the labels is to increase the height of the matrix. The only other option would be to decrease the font size, but I guess that's not what you want. So you can compute the ideal figure height based on the number of rows in the matrix and the font size of the labels. When you save the resulting plot you get the expected result. It seems that the height of the GUI window which you see when calling plt.show() is limited to the screen height:

    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    # create some random data
    data = np.random.rand(150, 10)
    
    # get the tick label font size
    fontsize_pt = plt.rcParams['ytick.labelsize']
    dpi = 72.27
    
    # comput the matrix height in points and inches
    matrix_height_pt = fontsize_pt * data.shape[0]
    matrix_height_in = matrix_height_pt / dpi
    
    # compute the required figure height 
    top_margin = 0.04  # in percentage of the figure height
    bottom_margin = 0.04 # in percentage of the figure height
    figure_height = matrix_height_in / (1 - top_margin - bottom_margin)
    
    
    # build the figure instance with the desired height
    fig, ax = plt.subplots(
            figsize=(6,figure_height), 
            gridspec_kw=dict(top=1-top_margin, bottom=bottom_margin))
    
    # let seaborn do it's thing
    ax = sns.heatmap(data, ax=ax)
    
    # save the figure
    plt.savefig('/tmp/test.png')
    

    Result:

    0 讨论(0)
提交回复
热议问题