Search code examples
python-3.xmatplotlibaxis-labelsviolin-plot

How to rename the x-labels in a violinplot?


I have made a violinplot and want to rename the x-labels .

  ax = sns.violinplot(x="Week_Number", y="Ammonia", data=Res)

this is the output:

enter image description here

And What I want to Have is , rather than 1 I want Week 1 , than for 44 i Want Week 2 until Week 10 for 52.

Thanks Everyone


Solution

  • You're looking to set_xticklabels property (doc). To apply this function, you need to have the axis. There is the same for y labels with set_yticklabels.

    Here the code is adapted from Seaborn examples:

    # Import modules
    import seaborn as sns
    import numpy as np
    import matplotlib.pyplot as plt
    
    # Create your list of labels
    week_list = ["Week_" + str(i) for i in range(1, 10)]
    # ['Week_1', 'Week_2', 'Week_3', 'Week_4', 'Week_5', 'Week_6', 'Week_7', 'Week_8', 'Week_9']
    
    fig = plt.figure()                  # Create a new figure for getting axis
    ax = fig.add_subplot(111)           # Get the axis
    
    # Create a random dataset across several variables
    rs = np.random.RandomState(0)
    n, p = 40, 8
    d = rs.normal(0, 2, (n, p))
    d += np.log(np.arange(1, p + 1)) * -5 + 10
    
    # Use cubehelix to get a custom sequential palette
    pal = sns.cubehelix_palette(p, rot=-.5, dark=.3)
    
    # Show each distribution with both violins and points
    sns.violinplot(data=d, palette=pal, inner="points")
    
    week_list = ["Week_" + str(i) for i in range(1,10)]
    
    # Set the x labels
    ax.set_xticklabels(week_list)
    
    # Show figure
    plt.show()
    

    enter image description here