Home > Enterprise >  set_axisbelow() not moving secondary axis
set_axisbelow() not moving secondary axis

Time:05-20

I currently have some code to generate a figure with two different y axes, ax and ax2. I would like to have ax2 and its associated plot behind ax, but I have tried doing this using set_axisbelow(True), but this has been unsuccessful. How can this be done?

Below is my code:

#!/usr/local/bin/python3
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches

testpower = [524.007, 525.201, 526.394, 527.585, 528.842, 529.973, 530.946, 532.032, 533.526, 534.608, 535.689, 536.769, 537.848, 538.925, 540.001, 541.075, 542.148, 543.22, 544.29, 545.359]
testtime_min = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400]

testpower2 = [549.986, 551.049, 552.11, 553.17, 554.229]
testtime_min2 = [480, 500, 520, 540, 560]

growth1 = [-0.64, -0.42, 0.54, 0.32, 0.09, 0.7, 0.42, -0.26, 0.37, -0.07, -0.12, 0.21, -0.19, 0.28, 0.2, -0.05, -0.2, 0.03, -0.27, -0.20]
growth2 = [-0.64, -0.05, -0.22, -0.11, 0.04]


fig=plt.figure(figsize=(4.5,3.6))
ax=fig.add_subplot(1,1,1)
ax.grid(b=True, which='major', color='#eeeeee', linestyle='-', zorder=1, linewidth=0.4) # turn on major grid
ax.grid(b=True, which='minor', color='#eeeeee', linestyle='-', zorder=1, linewidth=0.4) # turn on minor grid
ax.set_ylabel('y1')
ax.set_xlabel('Time (min)')

ax2 = fig.add_subplot(111, sharex=ax , frameon=False)
ax2.yaxis.tick_right()
ax2.set_axisbelow(True)
ax2.yaxis.set_label_position("right") 
ax2.set_ylabel('y2', color='crimson')
ax2.spines['right'].set_color('crimson')
ax2.yaxis.label.set_color('crimson')
ax2.minorticks_on()
ax2.tick_params(direction='out', axis='y', which='both', pad=4, colors='crimson')
ax2.set_axisbelow(True) # put grid behind curves

ax.axhline(y=0, color='black', linestyle='dashed', alpha = 0.3)
ax.scatter(testtime_min, growth1,color='purple',linewidth=1,zorder = 3, s = 10)
ax.plot(testtime_min, growth1,color='purple',alpha = 0.5, linewidth=1,zorder = 3)

ax.scatter(testtime_min2, growth2,color='purple',linewidth=1,zorder = 3, s = 10)
ax.plot(testtime_min2, growth2,color='purple',alpha = 0.5, linewidth=1,zorder = 3)


ax2.plot(testtime_min, testpower, c = 'red',zorder=2)
ax2.plot(testtime_min2, testpower2, c = 'red')

plt.savefig('test.pdf', dpi=300, bbox_inches='tight', format='pdf')

CodePudding user response:

I think you need:

ax.set_zorder(ax2.get_zorder() 1)
ax.patch.set_visible(False)

enter image description here

  • Related