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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With