Matteo NNZ
Matteo NNZ

Reputation: 12645

Matplotlib: adding a third subplot in the plot

I am completely new to Matplotlib and I have written this code to plot two series that so far is working fine:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

list1 = [1,2,3,4]
list2 = [4,3,2,1]

somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart

gs = gridspec.GridSpec(3,1)

if not somecondition:
    ax = plt.subplot(gs[:,:]) #create the first subplot that will ALWAYS be there
    ax.plot(list1) #populate the "main" subplot
else:
    ax = plt.subplot(gs[:2, :])
    ax.plot(list1)
    ax = plt.subplot(gs[2, :]) #create the second subplot, that MIGHT be there
    ax.plot(list2) #populate the second subplot
plt.show()

What I would like to do is adding a third series to this plot, let's say:

list3 = [4,1,2,4]

What matters is that the first subplot (list1) has to be twice as bigger than the other two; for doing this I have used gridspace, but as I am really new I'm not being able to understand how I should set the parameter for this sample code to get the third one. Can anyone explain me how I should edit the block somecondition == True to get 3 subplots (first 1 twice bigger than the other 2 below) rather than just two? P.S. the code is executable.

Upvotes: 0

Views: 701

Answers (2)

kiriloff
kiriloff

Reputation: 26335

This is an example with Matplotlib subplots

import matplotlib.pyplot as plt
import numpy as np

x,y = np.random.randn(2,100)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2)
ax1.grid(True)
ax1.axhline(0, color='black', lw=2)

ax2 = fig.add_subplot(212, sharex=ax1)
ax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2)
ax2.grid(True)
ax2.axhline(0, color='black', lw=2)

plt.show()

it is using pyplot, and add_subplot with a quite straightforward syntax.

Upvotes: 1

proxi
proxi

Reputation: 1263

To get 2:1 ratio, you can use 4 rows, and make plots take 2, 1, 1 row respectively:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

list1 = [1,2,3,4]
list2 = [4,3,2,1]
list3 = [4,1,2,4]

somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart

gs = gridspec.GridSpec(4,1)

if not somecondition:
    ax = plt.subplot(gs[:,:]) #create the first subplot that will ALWAYS be there
    ax.plot(list1) #populate the "main" subplot
else:
    ax = plt.subplot(gs[:2, :])
    ax.plot(list1)
    ax = plt.subplot(gs[2, :]) #create the second subplot, that MIGHT be there
    ax.plot(list2) #populate the second subplot
    ax = plt.subplot(gs[3, :]) #create the second subplot, that MIGHT be there
    ax.plot(list3)
plt.show()

Upvotes: 0

Related Questions