pythonmatplotlibtwinx

matplotlib: Twinx() hides the minor grid of primary axis


I want to:

I can plot the graph perfectly with only one y-axis, BUT as soon as I uncomment "ax2 = ax1.twinx()", the minor gridlines of the primary axis disappear. Picture: The correct format with single plot, and the minor_grid-problem with two plots.

Thank you in advance!

def plot_graph(x, y1, label1, y2, label2, title):

fig, ax1 = plt.subplots()

# Plotting y-axis 1
ax1.set_xlabel('Time (s)')
ax1.set_ylabel(label1, color = "red")
ax1.grid(which='major',axis='both', color='black', linewidth=1)
ax1.grid(which='minor',axis='y',    color='gray',  linewidth=0.3)
ax1.tick_params(axis = 'y')
ax1.plot(x, y1, color = "red")

# Plotting secondary y-axis with the same x-axis 
ax2 = ax1.twinx()  # PROBLEM: this alone hides the ax1 minor grid
ax2.set_ylabel(label2, color = 'blue')   
ax2.plot(x,y2,color = 'blue')
ax2.tick_params(axis = 'y')

plt.minorticks_on()
plt.legend(loc='best')
plt.title(title)
plt.show()

return

Solution

  • Problem solved.

    1. "plt.minorticks_on()" needs to be called before "ax2 = ax1.twinx()".
    2. "axis='both'" in ax1.grid() does not work. => call separately for x and y axes.

    '''

    plot_graph(x, y1, label1, y2, label2, title):
    
    fig, ax1 = plt.subplots()
    
    #Plotting y-axis 1
    ax1.set_xlabel('Time (s)')
    ax1.set_ylabel(label1, color="red")
    
    ax1.grid(which='major',axis='x', color='black', linewidth=1)   # x major black
    ax1.grid(which='minor',axis='x', color='gray', linewidth=0.3)  # x minor gray
    ax1.grid(which='major',axis='y', color = 'k', linewidth=1)     # y major black
    ax1.grid(which='minor',axis='y', color = 'gray',linewidth=0.3) # y minor gray (this was not showing) 
    
    ax1.plot(x, y1, color = "red")
    
    plt.minorticks_on() # NEW PLACE - SOLUTION
    
    #Plotting secondary y-axis with the same x-axis 
    ax2 = ax1.twinx() 
    ax2.set_ylabel(label2, color = 'blue')   
    ax2.plot(x,y2,color = 'blue')
    ax2.tick_params(axis = 'y')
    
    #plt.minorticks_on()   # OLD PLACE
    
    plt.legend(loc='best')
    plt.title(title)
    plt.show(block=False)
    
    return
    

    ''' Image: Correct output