Search code examples
pythonplotseaborngradientkernel-density

Distribution Plot with Gradient Fill in Python


I'm trying to create a density plot with a gradient fill in python like this:

enter image description here

I've attempted to do so using this code:

plt.figure(figsize=(6, 1))
sns.kdeplot(data=df, x='Overall Rating', fill=True, palette='viridis')
...and
sns.kdeplot(data=df, x='Overall Rating', fill=True, cmap='viridis')

Neither work, both outputting this plot:

enter image description here

I've searched all over for a method to do this in python, but no luck. I've tried implementing the methods from this answer by @Diziet Asahi but can't wrap my head around it. Any help would really be appreciated!


Solution

  • You just need to grab the ax: ax = sns.kdeplot(...) and then execute the inner part of the for loop in @Diziet Asahi's solution with that ax.

    import matplotlib
    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np
    
    sns.set_theme(style='white')
    iris = sns.load_dataset('iris')
    ax = sns.kdeplot(data=iris, x='petal_length', fill=True)
    
    sns.despine()
    cmap = 'turbo'
    im = ax.imshow(np.linspace(0, 1, 256).reshape(1, -1), cmap=cmap, aspect='auto',
                   extent=[*ax.get_xlim(), *ax.get_ylim()], zorder=10)
    path = ax.collections[0].get_paths()[0]
    patch = matplotlib.patches.PathPatch(path, transform=ax.transData)
    im.set_clip_path(patch)
    
    plt.show()
    

    kdeplot with gradient fill