Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pylab - Adjust hspace for some of the subplots

I have a plot in which I want to have one panel separate from other four panels. I want the rest of the four panels to share the x axis. The figure is shown below. I want the bottom four panels to have shared x-axis. I tried

f = plt.figure()
ax6=f.add_subplot(511)
ax4=f.add_subplot(515)
ax1=f.add_subplot(512,sharex=ax4)
ax2=f.add_subplot(513,sharex=ax4)
ax3=f.add_subplot(514,sharex=ax4)

However, that does not work for me. The attached figure is made with

f = plt.figure()
ax6=f.add_subplot(511)
ax4=f.add_subplot(515)
ax1=f.add_subplot(512)
ax2=f.add_subplot(513)
ax3=f.add_subplot(514)

and then setting the xticks to none by

ax1.get_xaxis().set_ticklabels([])
ax2.get_xaxis().set_ticklabels([])
ax3.get_xaxis().set_ticklabels([])

using f.subplots_adjust(hspace=0) joins all the subplots. Is there a way to join only the bottom four panels?

Thanks! enter image description here

like image 593
toylas Avatar asked Mar 02 '15 22:03

toylas


People also ask

Which is used to adjust the distance among the subplots?

Using tight_layout() method to set the spacing between subplots.

Can the spacing be adjusted between subplots using Matplotlib?

MatPlotLib with Python Set the figure size and adjust the padding between and around the subplots. Add a grid layout to place subplots within a figure. Update the subplot parameters of the grid. Add a subplot to the current figure.

How do you increase the Figsize of a subplot?

To change figure size of more subplots you can use plt. subplots(2,2,figsize=(10,10)) when creating subplots.


1 Answers

It's easiest to use two separate gridspec objects for this. That way you can have independent margins, padding, etc for different groups of subplots.

As a quick example:

import numpy as np
import matplotlib.pyplot as plt

# We'll use two separate gridspecs to have different margins, hspace, etc
gs_top = plt.GridSpec(5, 1, top=0.95)
gs_base = plt.GridSpec(5, 1, hspace=0)
fig = plt.figure()

# Top (unshared) axes
topax = fig.add_subplot(gs_top[0,:])
topax.plot(np.random.normal(0, 1, 1000).cumsum())

# The four shared axes
ax = fig.add_subplot(gs_base[1,:]) # Need to create the first one to share...
other_axes = [fig.add_subplot(gs_base[i,:], sharex=ax) for i in range(2, 5)]
bottom_axes = [ax] + other_axes

# Hide shared x-tick labels
for ax in bottom_axes[:-1]:
    plt.setp(ax.get_xticklabels(), visible=False)

# Plot variable amounts of data to demonstrate shared axes
for ax in bottom_axes:
    data = np.random.normal(0, 1, np.random.randint(10, 500)).cumsum()
    ax.plot(data)
    ax.margins(0.05)

plt.show()

enter image description here

like image 128
Joe Kington Avatar answered Sep 22 '22 23:09

Joe Kington