0

There are a few examples showing how to use "shrink" for changing the colorbar. How can I automatically figure out what the shrink should be so the colorbar is equal to the height of the heatmap?

I don't have a matplotlib axis because I am using seaborn and plotting the heatmap from the dataframe.

    r = []
    r.append(np.arange(0,1,.1))
    r.append(np.arange(0,1,.1))
    r.append(np.arange(0,1,.1))
    df_cm = pd.DataFrame(r)

    sns.heatmap(df_cm, square=True, cbar_kws=dict(ticks=[df_cm.min().min(), df_cm.max().max()]))
    plt.tight_layout()
    plt.savefig(f'test.png', bbox_inches="tight")

enter image description here

001001
  • 530
  • 1
  • 4
  • 13
  • If you set `square=False` (the default), the colorbar will automatically have the correct size. – JohanC Mar 24 '22 at 14:45
  • @JohanC yes but I need it square – 001001 Mar 24 '22 at 14:46
  • @JohanC Sorry about that, added. – 001001 Mar 24 '22 at 14:53
  • You get access to the matplotlib axis via `ax = sns.heatmap(....)`. You'll need to first create the heatmap without colorbar, then create a "colorbar `ax` " for the colorbar (e.g. via `make_axes_locatable`), and then create the colorbar on the newly created ax. – JohanC Mar 24 '22 at 14:58
  • @JohanC It would be great if you could make an answer out of that. It seems I need to change up everything as the return from sns doesn't have `get_array` – 001001 Mar 24 '22 at 16:31
  • You could use `plt.colorbar(ax.collections[0], cax= ..., ticks=...)`. Note that `tight_layout` doesn't work if you have this kind of relation between the `ax`es. – JohanC Mar 24 '22 at 18:17

0 Answers0