pythonmatplotlibseabornhistogram2d

seaborn jointplot color by density


I am making 2d histograms for some data with millions of data points. matplotlib.hist2d(x,y,bins,norm=LogNorm()) works well and produces a plot in about 5 seconds, but I like the marginal histograms of seaborn.jointplot(). How do I color the points in seaborn.jointplot() with log density of points like in the attached matplotlib.hist2d() figure? Using KDE takes way too long (I give up after about a minute or so), and I have lots of figures to create. So time to 'get' colors is a factor. Alternatively, how do I add marginal histograms to matplotlib.hist2d()?

plt.hist2d(x,y,100,norm=LogNorm(),cmap='jet')

enter image description here

sns.jointplot(x=x, y=y)

enter image description here


Solution

  • There might be another direct way to get a color map in seaborn. I couldn't find any yet. Here is a hacky sample solution to get things done with some random data. As to your second problem, I would suggest to post a new question.

    The trick is to first create a jointplot using seaborn and then hide the 2d-scatter and re-plot it using plt.hist2d

    import seaborn as sns
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    
    # some random data
    x = np.random.normal(size=100000)
    y = x * 3.5 + np.random.normal(size=100000)
    
    ax1 = sns.jointplot(x=x, y=y)
    ax1.ax_joint.cla()
    plt.sca(ax1.ax_joint)
    
    plt.hist2d(x, y, bins=(100, 100), cmap=cm.jet);
    

    enter image description here