Tendero
Tendero

Reputation: 1166

Horizontal bar chart from right to left in matplotlib

The example code provided here generates this plot:

enter image description here

I want to know if it is possible to plot the exact same thing but "mirrored", like this:

enter image description here

Here is the sample code provided just in case the link stops working:

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


plt.rcdefaults()
fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center',
        color='green', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

Upvotes: 5

Views: 11709

Answers (2)

Nicola Meneghini
Nicola Meneghini

Reputation: 31

An alternative way would be simply to set inverted limits on the x-axis, just like this:

ax.set_xlim(14,0)

Upvotes: 3

Sheldore
Sheldore

Reputation: 39072

You were close, you forgot to put ax.invert_xaxis(). But still, you assigned the y-ticks on the left-hand side y-axis.

To assign the ticks on the right-hand side, you need to first create a twin x-axis (right-hand side y-axis) instance (here ax1) and then plot the bars on that. You can hide the left-hand side y-axis ticks and labels by passing [].

I present two ways to solve it (rest of the code remains the same except that now you use ax1 instead of ax)

Solution 1

ax.set_yticklabels([]) # Hide the left y-axis tick-labels
ax.set_yticks([]) # Hide the left y-axis ticks
ax1 = ax.twinx() # Create a twin x-axis
ax1.barh(y_pos, performance, xerr=error, align='center',
    color='green', ecolor='black') # Plot using `ax1` instead of `ax`
ax1.set_yticks(y_pos)
ax1.set_yticklabels(people)

Solution 2 (same output): Keep the plot on the left axis (ax), invert the x-axis, and set the y-ticklabels on ax1

ax.invert_yaxis()  # labels read top-to-bottom
ax.invert_xaxis()  # labels read top-to-bottom

ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks(y_pos)
ax2.set_yticklabels(people)

enter image description here

Upvotes: 5

Related Questions