1

I have a line and bar plot and am having trouble getting things plotted in the right order. I want grid lines behind everything, bars next, and the lines on top of everything. Below is what I've tried. Try #3 comes closest I suppose, but grid lines are on top of the bars:

import  os, sys
import matplotlib.pyplot as plt

dtnums = [1,2,3,4,5]
pop    = [20,25,75,32,5]
obs    = [0.0, 0.0, 0.21, 0.30, 0.10]

fig, ax1 = plt.subplots( figsize=(8,5) )
ax2 = ax1.twinx()

#--- Try #1
ax1.plot(dtnums, pop, color='blue', linewidth=3)
ax1.grid(True, axis='y')
ax2.bar(dtnums, obs, color='g')
plt.show()

Try #1

#--- Try #2
ax1.plot(dtnums, pop, color='blue', linewidth=3, zorder=10)
ax1.grid(True, axis='y',zorder=0)
ax2.bar(dtnums, obs, color='g', zorder=1)
plt.show()

Try #2

#--- Try #3
ax1.plot(dtnums, pop, color='blue', linewidth=3, zorder=2)
ax1.grid(True, axis='y',zorder=0)
ax2.bar(dtnums, obs, color='g', zorder=1)

ax1.set_axisbelow(True)
ax1.set_zorder(10)
ax1.patch.set_visible(False)
plt.show()

Try #3

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Jeff Baars
  • 11
  • 1

1 Answers1

0
import matplotlib.pyplot as plt

dtnums = [1,2,3,4,5]
pop    = [20,25,75,32,5]
obs    = [0.0, 0.0, 0.21, 0.30, 0.10]

fig, ax1 = plt.subplots(figsize=(8, 5))
ax2 = ax1.twinx()

# add this
ax2.set_axisbelow(True)

ax1.plot(dtnums, pop, color='blue', linewidth=3, zorder=2)

# change this from ax1 to ax2
ax2.grid(True, axis='y', zorder=0)

ax2.bar(dtnums, obs, color='g', zorder=1)

ax1.set_axisbelow(True)
ax1.set_zorder(10)
ax1.patch.set_visible(False)
plt.show()

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158