Horizontal bar chart from right to left in matplotlib
Clash Royale CLAN TAG#URR8PPP
Horizontal bar chart from right to left in matplotlib
The example code provided here generates this plot:
I want to know if it is possible to plot the exact same thing but "mirrored", like this:
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()
-performance
xticks
1 Answer
1
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 . Rest of the code remains the same except that now you use
ax1
instead of ax
. You can name ax1
as you want.
ax1
ax1
ax
ax1
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`
Solution 2 (same output):
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)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
A trick-way is to plot
-performance
, and change thexticks
to positive.– Lucas
7 mins ago