Search code examples
pythonmatplotliblabeldistributionviolin-plot

shifting violin plot horizontally in python


i have 8 different arryas that i want to plot using violin plot to compare distributions, this is how I plotted:

plt.violinplot(alpha_g159)
plt.violinplot(alpha_g108)
plt.violinplot(alpha_g141)
plt.violinplot(alpha_g110)
plt.violinplot(alpha_g115)
plt.violinplot(alpha_g132)
plt.violinplot(alpha_g105)
plt.violinplot(alpha_g126)

And I have this plot:

enter image description here

Actually what I want to do, is to shift each plot horizontally (along the x-axis) so they would not overlap, and then add on the x-axis the label of each plot.

Could anyone guide me on how to do that? i tried adding for example alpha_108+x0with x0=2but it just shifts it vertically.


Solution

  • You can achieve this by putting your data into a list. Matplotlib than plots the individual plots side by side.

    import matplotlib.pyplot as plt
    import numpy as np
    
    # put your data in a list like this:
    # data = [alpha_g159, alpha_g108, alpha_g141, alpha_g110, alpha_g115, alpha_g132, alpha_g105, alpha_g126]
    # as I do not have your data I created some test data
    data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 9)]
    plt.violinplot(data)
    
    labels = ["alpha_g159", "alpha_g108", "alpha_g141", "alpha_g110", "alpha_g115", "alpha_g132", "alpha_g105", "alpha_g126"]
    # add the labels (rotated by 45 degrees so that they do not overlap)
    plt.xticks(range(1, 9), labels, rotation=45)
    
    # Tweak spacing to prevent clipping of tick-labels
    plt.subplots_adjust(bottom=0.3)
    
    plt.show()
    

    resulting plot