anon
anon

Reputation:

Matplotlib: Grid lines behind bars on twinned axes?

I'm plotting two series on one chart using twiny() and want the grid lines behind the bars. However, by default the behaviour is mixed: in front of elements of the original axes and behind the twin's.

Neither axes.set_axisbelow(True) nor zorder=0 with the grid call fixes this. Is this a bug in matplotlib? Anyone know of a work around?

Here's an example to illustrate:

import matplotlib, matplotlib.pyplot as plt
print('matplotlib: {}'.format(matplotlib.__version__))

series1 = [1.25,2.25,3]
series2 = [12,9.75,6.75]
categories = ['A','B','C']

fig, axes1 = plt.subplots(nrows=1,ncols=1)
axes2 = axes1.twiny()

axes1.barh(categories, series1, color='red', align='edge', height=-0.4)
axes2.barh(categories, series2, color='blue', align='edge', height=+0.4)
axes1.set_axisbelow(True)
axes2.set_axisbelow(True)

axes1.grid(axis='x')
axes2.grid(axis='x')
plt.show()

matplotlib v. 3.2.2

Upvotes: 1

Views: 1005

Answers (1)

JohanC
JohanC

Reputation: 80409

Everything drawn on one axis (including the grid) is always or completely before or completely behind everything drawn on the other axis. The only solution in your case is to only draw a grid for axes1, removing the call to the grid for the other axis.

Upvotes: 1

Related Questions