Seaborn Heatmap Colorbar Label as Percentage

前端 未结 4 969
醉话见心
醉话见心 2020-12-14 11:31

Given this heat map:

import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_da         


        
相关标签:
4条回答
  • 2020-12-14 11:54

    You need to be able to access the colorbar object. It might be buried in the figure object somewhere, but I couldn't find it, so the easy thing to do is just to make it yourself:

    import numpy as np; np.random.seed(0)
    import seaborn as sns; sns.set()
    uniform_data = np.random.rand(10, 12)
    ax = sns.heatmap(uniform_data, cbar=False, vmin=0, vmax=1)
    cbar = ax.figure.colorbar(ax.collections[0])
    cbar.set_ticks([0, 1])
    cbar.set_ticklabels(["0%", "100%"])
    

    0 讨论(0)
  • 2020-12-14 12:04

    iterating on the solution of @mwaskom, without creating the colorbar yourself:

    import numpy as np
    import seaborn as sns
    data = np.random.rand(8, 12)
    ax = sns.heatmap(data, vmin=0, vmax=1)
    cbar = ax.collections[0].colorbar
    cbar.set_ticks([0, .2, .75, 1])
    cbar.set_ticklabels(['low', '20%', '75%', '100%'])
    

    0 讨论(0)
  • 2020-12-14 12:06

    You should get the colour bar object and then get the relevant axis object:

    import matplotlib.pyplot as plt
    from matplotlib.ticker import PercentFormatter
    
    fig, ax = plt.subplots()
    sns.heatmap(df, ax=ax, cbar_kws={'label': 'My Label'})
    cbar = ax.collections[0].colorbar
    cbar.ax.yaxis.set_major_formatter(PercentFormatter(1, 0))
    
    0 讨论(0)
  • 2020-12-14 12:19

    Well, I had a similar problem and figured out how to properly set a formatter. Your example would become something like:

    import numpy as np; np.random.seed(0)
    import seaborn as sns; sns.set()
    
    uniform_data = np.random.rand(10, 12)
    uniform_data = 100 * uniform_data
    
    sns.heatmap(uniform_data,
                cbar_kws={'format': '%.0f%%'})
    

    So, what you have to do is to pass an old-style string formatter to add percentages to colorbar labels. Not exactly what I would name self-evident, but works...

    To show only the first and last, then you add vmax, vmin and an extra parameter to cbar_kws:

    sns.heatmap(uniform_data,
                cbar_kws={'format': '%.0f%%', 'ticks': [0, 100]},
                vmax=100,
                vmin=0)
    
    0 讨论(0)
提交回复
热议问题