Gonzalo Garcia
Gonzalo Garcia

Reputation: 6612

How to Alternate x labels in seaborn?

I'm trying to plot a countplot with seaborn with the following code:

sns.set(rc={'figure.figsize':(15,10)})
ax = sns.countplot(hue="PRODUCTS", x="CATEGORIES",data=df)
plt.show()

But the categorical labels would overlap each other. Like this:

enter image description here

I could succesfully rotate the xticks but I would like to alternate them like in the following image:

enter image description here

In the previous image this method was used:

ax = sns.barplot(data=to_plot, x='Channel', y='% of leads assigned')
tweak_x_ticks(ax, alternate=True)

but tweak_x_ticks it's not a seaborn or matplotlib built-in method. How can I alternate the x labels? In other words, how can you define tweak_x_ticks?

Upvotes: 1

Views: 467

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339170

A possible implementation of tweak_x_ticks could be (untested):

def tweak_x_ticks(ax, alternate=True):
    if not alternate:
        return
    ax.figure.canvas.draw()
    ax.set_xticklabels(["\n"*(i%2) + label.get_text() for i, label in enumerate(ax.get_xticklabels())])

Upvotes: 1

Related Questions