pythonmatplotlibseabornridgeline-plot

Adding y-axis on right side to Ridge Plot in Seaborn


I would like to add a sample y-axis tick on the right side of the Ridge plot, to know what is the range of values of all the plots. Preferably I would like to add it only to one of the subplots and not to all of them.

My plot is based on the seaborn 'ridge plot' example at: https://seaborn.pydata.org/examples/kde_ridgeplot.html

I've tried the following code with no luck:

g.set(yticks=[0,200])
g.set_y_label_position("right")
g.set_ylabels('[Range]',fontsize=9,fontweight="normal")

Solution

  • If you want to modify one particular axes from a FacetGrid, you can get a reference from the list g.axes

    Here is how I would go about it

    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})
    
    # Create the data
    rs = np.random.RandomState(1979)
    x = rs.randn(500)
    g = np.tile(list("ABCDEFGHIJ"), 50)
    df = pd.DataFrame(dict(x=x, g=g))
    m = df.g.map(ord)
    df["x"] += m
    
    # Initialize the FacetGrid object
    pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
    g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal)
    
    # Draw the densities in a few steps
    g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)
    g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2)
    g.map(plt.axhline, y=0, lw=2, clip_on=False)
    
    
    # Define and use a simple function to label the plot in axes coordinates
    def label(x, color, label):
        ax = plt.gca()
        ax.text(0, .2, label, fontweight="bold", color=color,
                ha="left", va="center", transform=ax.transAxes)
    
    
    g.map(label, "x")
    
    #
    # Changes from seaborn example below this point
    #
    
    # Set the subplots to overlap
    g.fig.subplots_adjust(hspace=-.25, right=0.9)
    
    # Remove axes details that don't play well with overlap
    g.set_titles("")
    #g.set(yticks=[])
    g.despine(bottom=True, left=True, right=False, top=True, offset=5)
    
    for ax in g.axes.ravel():
        if ax.is_first_row():  # can use .is_last_row() to show spine on the bottom plot instead
            ax.yaxis.tick_right()
            ax.yaxis.set_label_position("right")
            ax.set_ylabel("MW")
        else:
            ax.spines['right'].set_visible(False)
            [l.set_visible(False) for l in ax.get_yticklabels()]  # necessary because y-axes are shared
    

    enter image description here