Question

I need to compare multiple versions of a list of spectra and I am generating a figure object for each spectrum where I plan on showing the different versions of the same spectrum. Each version of each spectrum will have two "wings" I want to show on the same page. To do so I do something along the lines of (I represent the spectra as numpy arrays, I normally get them from fits files):

import os
import sys
import numpy as np
import matplotlib.pyplot as mplt
import matplotlib.gridspec as gs
import numpy.random as rnd

PageGrid = gs.GridSpec( 11, 1, hspace = 0.0)

Spec1 = rnd.randint(1, 100, 100)
Spec2 = rnd.randint(1, 100, 100)
Spec3 = rnd.randint(1, 100, 100)

LeftSpecList = ['Spec1', 'Spec2', 'Spec3']

RightSpecList = ['Spec1', 'Spec2', 'Spec3']

for leftSpec in LeftSpecList:
    fig = mplt.figure(str(leftSpec))
    axTop = fig.add_subplot( PageGrid[:5, :] )
    axTop.plot(eval(leftSpec))


for rightSpec in RightSpecList:
    fig = mplt.figure(str(rightSpec))
    axBottom = fig.add_subplot( PageGrid[6:, :] )       
    axBottom.plot(eval(rightSpec))

Then I have a second list of spectra I want to plot on top of the other ones (which might or not have the same lenght):

LeftSpecListNew = ['Spec1', 'Spec2']

RightSpecListNew = ['Spec2', 'Spec3']

for leftSpec in LeftSpecList:
    fig = mplt.figure(str(leftSpec))
    axTop.plot(eval(leftSpec))


for rightSpec in RightSpecList:
    fig = mplt.figure(str(rightSpec))
    axBottom.plot(eval(leftSpec))

mplt.show()

but when I do that, it prints all on the first figure. Any ideas?

Was it helpful?

Solution

axTop and axBottom are overwritten in the first two loops. You need to keep track of each top and bottom axis for each figure. Something like this should do what you want.

axTopDict = {}
for leftSpec in LeftSpecList:
    fig = mplt.figure(str(leftSpec))
    axTop = fig.add_subplot( PageGrid[:5, :] )
    axTop.plot(eval(leftSpec),'ro')
    axTopDict[leftSpec] = axTop # associate this axis with this figure name 

axBottomDict = {}
for rightSpec in RightSpecList:
    fig = mplt.figure(str(rightSpec))
    axBottom = fig.add_subplot( PageGrid[6:, :] )       
    axBottom.plot(eval(rightSpec),'b*')
    axBottomDict[rightSpec] = axBottom # associate this axis with this figure name 

LeftSpecListNew = ['Spec1', 'Spec2']

RightSpecListNew = ['Spec2', 'Spec3']

for leftSpec in LeftSpecList:
    fig = mplt.figure(str(leftSpec))
    axTop = axTopDict[leftSpec] # get the top axis associated with this figure name
    axTop.plot(eval(leftSpec),'m')


for rightSpec in RightSpecList:
    fig = mplt.figure(str(rightSpec))
    axBottom = axBottomDict[rightSpec] # get the bottom axis associated with this figure name
    axBottom.plot(eval(leftSpec),'g')

mplt.show()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top