1

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

Antinomial
  • 83
  • 2
  • 7
  • 2
    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. – JohanC Jun 26 '20 at 22:13
  • 3
    You can get away for this specific case by removing grid on the second axis (that is to say replace `axes2.grid(axis='x')` by `axes2.grid(False)`). However it will not render well if the grids of the two axes are not superposed. You can find how to set ticks in this topic: https://stackoverflow.com/questions/24943991/change-grid-interval-and-specify-tick-labels-in-matplotlib – bousof Jun 26 '20 at 22:30
  • 1
    @JohanC 's comment is exactly correct and should be posted as an answer. – tacaswell Jun 26 '20 at 23:53

1 Answers1

1

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.

JohanC
  • 71,591
  • 8
  • 33
  • 66