Getting colorbar in a hex jointplot
Asked Answered
T

2

13

I'm interested in using the seaborn joint plot for visualizing correlation between two numpy arrays. I like the visual distinction that the kind='hex' parameter gives, but I would also like to know the actual count that different shades correspond to. Does anyone know how to put this legend on the side or even on the plot? I tried looking at the documentation and couldn't find it.

Theurich answered 17/3, 2015 at 10:23 Comment(2)
I have been looking for this as well, it seems that they have not implemented it yet. Say if you find a solution.Negus
You should use plt.hexbin directly and then add a colorbar (which is waht I assume you mean by "legend" with plt.colorbar.Unfathomable
H
15

EDIT: updated to work with new Seaborn ver.

You need to do it manually by making a new axis with add_axes and then pass the name of the ax to plt.colorbar().

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

x = np.random.normal(0.0, 1.0, 1000)
y = np.random.normal(0.0, 1.0, 1000)
hexplot = sns.jointplot(x, y, kind="hex")
plt.subplots_adjust(left=0.2, right=0.8, top=0.8, bottom=0.2)  # shrink fig so cbar is visible
# make new ax object for the cbar
cbar_ax = hexplot.fig.add_axes([.85, .25, .05, .4])  # x, y, width, height
plt.colorbar(cax=cbar_ax)
plt.show()

Seaborn hexplot with colorbar

Sources: I almost gave up after I read a dev say that the

"work/benefit ratio [to implement colorbars] is too high"

but then I eventually found this solution in another issue.

Haas answered 28/4, 2015 at 2:3 Comment(8)
This doesn't seem to be working for me. Do you know what versions are (were) you using for this?Rhett
@Rhett I updated my answer with a full working example. Your problem was probably that the colorbar was being plotted off to the right of the canvas, so I added a subplots_adjust() line to work around the issue. (FYI tight_layout is not compatible with this Axes object so that is not an option)Haas
Fantastic. Thanks for such a quick response!. I'll give this a go on Monday.Rhett
@Rhett happy to help, let me know if you have any issuesHaas
@VictorAguiar @Bollenhenk Seaborn deprecated it's internal plt, I updated my answer to work with the new version. Cheers.Haas
Good to know. Thank you, @HaasCathrinecathryn
How can I add a title on top of this figure? plt.title places really in the wrong positionBelicia
@makis try suptitleHaas
K
2

The following has worked for me:

t1 = sns.jointplot(data=df, x="originalestimate_hours", y="working_hours_per_day_created_target", hue="status")
t1.ax_joint.legend_._visible=False
t1.fig.legend(bbox_to_anchor=(1, 1), loc=2)
Kramer answered 27/4, 2021 at 17:20 Comment(1)
This didn't work for me. I get an error AttributeError: 'NoneType' object has no attribute '_visible'Nolen

© 2022 - 2024 — McMap. All rights reserved.