Search code examples
pythongraphseabornswarmplot

Seaborn Swarmplot Axis Interval Formatting


Currently, my seaborn swarm plot has the x axis intervals too close together resulting in a plot that looks like this: image Below is my current code where. Toy data x-values (32, 34, 76, 34, 64, 34, 23, 76, 34, 63, 75, 34, 76, 34, 34, 45, 56, 67, 34, 56) Y-values (0,0,1,0,1,1,0,1,0,1,0,1,1,0,0,0,1,0,1,0)

sns.swarmplot(x="age", y="sex", hue="target", palette=["green", "red"], data=df)

Is there a way to format the intervals? For instance, I would like the x-axis to have a total of 5 labels total. When I plot using relplot the axis labels look fine, but it messes up when I switch to swarmplot. I cannot seem to find info on this anywhere. All the other questions asked that I found do not seem to work on swarmplots.

This post here (post) is very similar to my question, however I am not using plt but instead am using seaborn. Any help much appreciated.


Solution

  • You can get access to all matplotlib functionallity via ax = sns.swarmplot(...) and then call e.g. ax.get_xticks().

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns
    
    N = 100
    df = pd.DataFrame({'x': np.random.randint(30, 80, N, dtype=int),
                       'y': np.random.randint(0, 2, N),
                       'target': np.random.randint(0, 2, N)})
    ax = sns.swarmplot(x='x', y='y', hue="target", palette=["green", "red"], data=df)
    ticks = ax.get_xticks()
    labels = ax.get_xticklabels()
    ax.set_xticks(ticks[4::5])
    ax.set_xticklabels(labels[4::5])
    ax.set_yticks([0, 1])
    plt.show()
    

    demo plot