basket_case
basket_case

Reputation: 37

Adding a variable number of sub-plots in a loop. add_subplot

I will always have at minimum 2 sub-plots which should be positioned on top of each other without the graph areas touching. They should be wider than they are tall.

Then if a certain condition is met (in this case if there is a specific type of peak in the data) I would like this peak plotted on it's own sub-plot on the right of the other two plots. This third plot should be taller than it is wide. There could be any number of these extra plots including none. I already have the positions I would like to plot between I just don't know how to make add_subplot do what I want.

The first two plots are working perfectly, and I would have thought the one in the loop would add an nth subplot that is 1 wide and 2 tall, but I get the error: IndexError: index out of range.

The code below is simply trying to get things the right shape (I know I'm not plotting any data yet).

fig = pl.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)
n = 2

#if there is a peak plot it on this subplot
    peak = fig.add_subplot(1, 2, n)
    n =+ 1

Upvotes: 1

Views: 874

Answers (1)

Amy Teegarden
Amy Teegarden

Reputation: 3972

You can use GridSpec to create two plots. Later, you can move those plots over and add a third if you want to. When you call the update method on a GridSpec object, you can pass in parameters that tell it where to put the edges of the entire grid. You can play with the left and right parameters to make the subplots the desired width.

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
peak = True
gs1 = GridSpec(1, 2)
for sub in gs1:
  #make axes for two default plots
  ax = plt.subplot(sub)
if peak == True:
  #move default plots to the left 
  gs1.update(right = .75)
  #add new plot
  gs2 = GridSpec(1, 1)
  #move plot to the right
  gs2.update(left = .8)
  ax = plt.subplot(gs2[0, 0])
plt.show()

Upvotes: 1

Related Questions