Reputation: 181
When creating overlaid bar charts with two different height scales using Axes.twinx()
, I cannot set visible the vertical grid lines of the 'twin' axis set. The horizontal lines work fine though. Any thoughts on how to resolve this?
Below is some example code that illustrates what I want to do and what I cannot do. As seen, the vertical grid lines are hidden by the red bars of ax2
, whereas I want the grid lines to be visible through all bars.
# Create figure and figure layout
ax1 = plt.subplot()
ax2 = ax1.twinx()
# Example data
x = [0, 1, 2, 3, 4, 5]
h1 = [55, 63, 70, 84, 73, 93]
h2 = [4, 5, 4, 7, 4, 3]
# Plot bars
h1_bars = ax1.bar(x, h1, width=0.6, color='darkblue')
h2_bars = ax2.bar(x, h2, width=0.6, color='darkred')
# Set y limits and grid visibility
for ax, ylim in zip([ax1, ax2], [100, 10]):
ax.set_ylim(0, ylim)
ax.grid(True)
The error comes about because the vertical grid lines of ax2
are not set visible. This can be tested by setting ax1.grid(False)
, in which case there are only horizontal grid lines.
I have tried all combinations of ax1.xaxis.grid(True)
, ax1.yaxis.grid(True)
, ax2.xaxis.grid(True)
and ax2.yaxis.grid(True)
without any luck. Any help on this matter deeply appreciated!
Upvotes: 2
Views: 2175
Reputation: 339120
You may revert the role of ax1 and ax2, such that the blue bars are on ax2 and the red ones on ax1. Then you need to put the twin axes in the background and tick the respective y axes on the other side of the plot.
import matplotlib.pyplot as plt
# Create figure and figure layout
ax1 = plt.subplot()
ax2 = ax1.twinx()
# Example data
x = [0, 1, 2, 3, 4, 5]
h1 = [55, 63, 70, 84, 73, 93]
h2 = [4, 5, 4, 7, 4, 3]
# Plot bars
h1_bars = ax2.bar(x, h1, width=0.6, color='darkblue')
h2_bars = ax1.bar(x, h2, width=0.6, color='darkred')
# Set y limits and grid visibility
for ax, ylim in zip([ax1, ax2], [10, 100]):
ax.set_ylim(0, ylim)
ax.grid(True)
ax1.set_zorder(1)
ax1.patch.set_alpha(0)
ax2.set_zorder(0)
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()
plt.show()
Upvotes: 2