Julkar9
Julkar9

Reputation: 2110

Right align horizontal seaborn barplot

How can I make the horizontal seaborn barplot right aligned / mirrored

import matplotlib.pyplot as plt
import seaborn as sns

x = ['x1', 'x2', 'x3']
y = [4, 6, 3]
sns.barplot(x=y, y=x, orient='h')
plt.show()  

The default horizontal barplot looks like this
enter image description here

I want to have something like this (with proper xticks)
enter image description here

Upvotes: 3

Views: 2026

Answers (2)

Zephyr
Zephyr

Reputation: 12496

In order to invert the x axis, you can use:

ax.invert_xaxis()

Then, in order to move the labels to the right, you can use:

plt.tick_params(axis = 'y', left = False, right = True, labelleft = False, labelright = True)

or, shorter:

ax.yaxis.tight_right()

Complete Code

import matplotlib.pyplot as plt
import seaborn as sns

x = ['x1', 'x2', 'x3']
y = [4, 6, 3]
ax = sns.barplot(x=y, y=x, orient='h')

ax.invert_xaxis()
ax.yaxis.tick_right()

plt.show() 

enter image description here

Upvotes: 4

tmdavison
tmdavison

Reputation: 69056

You can just change the matplotlib x-axis limits. An easy way to do this is capture the Axes instance returned by sns.barplot, and then use ax.set_xlim on that.

Then you can use ax.yaxis.set_label_position('right') and ax.yaxis.set_ticks_position('right') to move the ticks and axis labels to the right.

For example:

import matplotlib.pyplot as plt
import seaborn as sns

x = ['x1', 'x2', 'x3']
y = [4, 6, 3]
ax = sns.barplot(x=y, y=x, orient='h')
ax.set_xlim(ax.get_xlim()[1], ax.get_xlim()[0])

ax.yaxis.set_label_position('right')
ax.yaxis.set_ticks_position('right')

plt.show()

enter image description here In that example, I grabbed the existing limits and just reversed them. Alternatively, you could just set them explicitly, making sure the first number is the upper limit, to ensure the reversed scale. For example:

ax.set_xlim(6.5, 0)

A final alternative is to use the built in ax.invert_xaxis() function

Upvotes: 1

Related Questions