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()
There is an option in Format Axis dialog for reversing the axis order. Tip: In bar chart, reserve the x axis with righting click the x axis and selecting the Format Axis from context menu, then checking the Values in reverse order in the Format Axis dialog box. 3. Close the dialog, now the y axis order is reversed.
By using plt. subplot() method we create two subplots side by side. plt. bar() method is used to create multiple bar chart graphs.
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)
An alternative way would be simply to set inverted limits on the x-axis, just like this:
ax.set_xlim(14,0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With