Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib with odd number of subplots

Tags:

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()
like image 452
LeoC Avatar asked Feb 26 '15 09:02

LeoC


1 Answers

To put it simply you make your subplots call for an even number (in this case 6 plots):

f, ax = plt.subplots(3, 2, figsize=(12, 15))

Then you delete the one you don't need:

f.delaxes(ax[2,1]) #The indexing is zero-based here

This question and response are looking at this in an automated fashion but i thought it worthwhile to post the basic use case here.

like image 100
DannyMoshe Avatar answered Oct 07 '22 12:10

DannyMoshe