Search code examples
pythonmatplotlibsubplot

How to create an odd number of subplots


I'm trying to create a plotting function that takes as input the number of required plots and plots them using pylab.subplots and the sharex=True option. If the number of required plots is odd, then I would like to remove the last panel and force the tick labels on the panel right above it. I can't find a way of doing that and using the sharex=True option at the same time. The number of subplots can be quite large (>20).

Here's sample code. In this example I want to force xtick labels when i=3.

import numpy as np
import matplotlib.pylab as plt

def main():
    n = 5
    nx = 100
    x = np.arange(nx)
    if n % 2 == 0:
        f, axs = plt.subplots(n/2, 2, sharex=True)
    else:
        f, axs = plt.subplots(n/2+1, 2, sharex=True)
    for i in range(n):
        y = np.random.rand(nx)
        if i % 2 == 0:
            axs[i/2, 0].plot(x, y, '-', label='plot '+str(i+1))
            axs[i/2, 0].legend()
        else:
            axs[i/2, 1].plot(x, y, '-', label='plot '+str(i+1))
            axs[i/2, 1].legend()
    if n % 2 != 0:
        f.delaxes(axs[i/2, 1])
    f.show()


if __name__ == "__main__":
     main()

Solution

  • If you replace last if in your main function with this:

    if n % 2 != 0:
        for l in axs[i/2-1,1].get_xaxis().get_majorticklabels():
            l.set_visible(True)
        f.delaxes(axs[i/2, 1])
    
    f.show()
    

    It should do the trick:

    Plot