python-3.xmatplotlibz-order

Zorder in plots with different x-axis in matplotlib


How to get blue points in front of the gray points, please? Why the order is not working?

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(10, 6))

ax3 = ax.twiny()
ax3.errorbar([1, 2, 3, 4], [1, 2, 3, 4], yerr = [1, 2, 3, 4], fmt='o', color='gray', zorder = 1)
ax3.plot([-1,4], [1,2], c = 'black', zorder = 2)
ax3.tick_params(axis='x')
ax3.tick_params(axis='x', colors='gray')
ax3.set_xlim(-1,4)

ax.tick_params(axis='x')
ax.tick_params(axis='x', colors='mediumblue')
ax.grid(color='grey', linestyle='-', linewidth=0.5, zorder = 1)
ax.errorbar([1.1, 2.1, 3.1, 4.1, 2.91], [1.1, 2.1, 3.1, 4.1,2], yerr = [1.1, 2.1, 3.1, 4.1,1], fmt='o', color='mediumblue', zorder = 4, capsize=0.1)

plt.tight_layout()
plt.show()

enter image description here


Solution

  • You can set the order using ax.set_zorder(ax3.get_zorder()+1); ax.patch.set_visible(False) which will help bring the blue line in front.

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots(figsize=(10, 6))
    
    ax3 = ax.twiny()
    ax3.errorbar([1, 2, 3, 4], [1, 2, 3, 4], yerr = [1, 2, 3, 4], fmt='o', color='gray', zorder = 1)
    ax3.plot([-1,4], [1,2], c = 'black', zorder = 2)
    ax3.tick_params(axis='x')
    ax3.tick_params(axis='x', colors='gray')
    ax3.set_xlim(-1,4)
    
    ax.tick_params(axis='x')
    ax.tick_params(axis='x', colors='mediumblue')
    ax.grid(color='grey', linestyle='-', linewidth=0.5, zorder = 1)
    ax.errorbar([1.1, 2.1, 3.1, 4.1, 2.91], [1.1, 2.1, 3.1, 4.1,2], yerr = [1.1, 2.1, 3.1, 4.1,1], fmt='o', color='mediumblue', zorder = 4, capsize=0.1)
    
    ax.grid(axis='y')
    ax.set_zorder(ax3.get_zorder()+1)
    ax.patch.set_visible(False)
    
    plt.tight_layout()
    plt.show()
    

    enter image description here