Search code examples
matplotlibaxissubplot

Why do xticks and xtick labels disappear when using plt.subplots_adjust?


I want to produce a simple 2x2 set of plots using matplotlib, where the space between the subplots is removed; the xtick and ytick labels are present on the bottom of the bottom plots and on the left of the left hand plots respectively, but there should be tick marks on the left and bottom axes of all 4 plots.

i.e. I would like the following 4 plots, but with the xtick and ytick labels removed on the interior axes and the space between the plots closed up.

4 plots but with gaps between them

So here is some code I tried, which almost does the job. I simply suppressed the interior xticklabels and yticklabels using set_xticklabels and set_yticklabels and then closed up the space between the plots using subplots_adjust.

However, I am baffled as to where the interior xaxis ticks have gone (note the interior yaxis ticks are still present as required) and I cannot work out how to get them to appear? NB: The set_xticklabels([]) statements are redundant too - the xtick labels are also suppressed.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 10, 1)
y = np.arange(1, 10, 1)

fig1, axs = plt.subplots(2, 2, figsize=(8,8))

for i in [0, 1]:

    axs[i,0].scatter(x, y)
    axs[i,1].scatter(x, y)
    axs[i,1].set_yticklabels([])

axs[0,0].set_xticklabels([])
axs[0,1].set_xticklabels([])
    
plt.subplots_adjust(hspace=0, wspace=0)  
plt.show()    

produces

Spaces removed but where are the interior xaxis ticks?


Solution

  • I found that adding .tick_params(direction='in') restores the ticks:

    enter image description here

    The ticks were originally on the outside and got covered by the abutting plots.

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(1, 10, 1)
    y = np.arange(1, 10, 1)
    
    fig1, axs = plt.subplots(2, 2, figsize=(8,8))
    
    for i in [0, 1]:
    
        axs[i,0].scatter(x, y)
        axs[i,1].scatter(x, y)
        axs[i,1].set_yticklabels([])
        
        #Enable ticks on inside
        axs[i, 0].tick_params(direction='in')
        axs[i, 1].tick_params(direction='in')
    
    plt.subplots_adjust(hspace=0, wspace=0)  
    plt.show()