Skip to content

Commit 2edb196

Browse files
committed
clean up plot routines
1 parent 5362786 commit 2edb196

File tree

1 file changed

+50
-57
lines changed

1 file changed

+50
-57
lines changed

pydl/pydlspec2d/spec1d.py

Lines changed: 50 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,6 @@
99
import numpy as np
1010
from numpy.linalg import solve
1111
try:
12-
import matplotlib
13-
# TODO: Sometimes this interferes with notebooks, other times not.
14-
# Maybe don't set this at import time.
15-
# matplotlib.use('Agg')
16-
matplotlib.rcParams['figure.figsize'] = (16.0, 12.0)
1712
import matplotlib.pyplot as plt
1813
from matplotlib.font_manager import FontProperties
1914
except ImportError:
@@ -23,6 +18,11 @@
2318
from astropy.io import ascii, fits
2419
from . import Pydlspec2dException, Pydlspec2dUserWarning
2520

21+
#
22+
# Used for automated matplotlib plots.
23+
#
24+
_default_figsize = (16.0, 12.0)
25+
2626
#
2727
# Used by findspec
2828
#
@@ -782,24 +782,22 @@ def plot_eig(filename, title='Unknown'):
782782
title = 'CV Stars: Eigenspectra'
783783
else:
784784
raise ValueError('Unknown template type!')
785-
base, ext = filename.split('.')
786-
spectrum = fits.open(filename)
787-
newloglam0 = spectrum[0].header['COEFF0']
788-
objdloglam = spectrum[0].header['COEFF1']
789-
spectro_data = spectrum[0].data
790-
spectrum.close()
785+
base, ext = os.path.splitext(filename)
786+
with fits.open(filename, mode='readonly') as hdulist:
787+
newloglam0 = hdulist[0].header['COEFF0']
788+
objdloglam = hdulist[0].header['COEFF1']
789+
spectro_data = hdulist[0].data
791790
(neig, ndata) = spectro_data.shape
792791
newloglam = np.arange(ndata) * objdloglam + newloglam0
793792
lam = 10.0**newloglam
794-
fig = plt.figure(dpi=100)
795-
ax = fig.add_subplot(111)
793+
fig, ax = plt.subplots(1, 1, figsize=_default_figsize, dpi=100)
796794
colorvec = ['k', 'r', 'g', 'b', 'm', 'c']
797795
for l in range(neig):
798796
_ = ax.plot(lam, spectro_data[l, :],
799797
colorvec[l % len(colorvec)]+'-', linewidth=1)
800-
ax.set_xlabel(r'Wavelength [$\AA$]')
801-
ax.set_ylabel('Flux [Arbitrary Units]')
802-
ax.set_title(title)
798+
_ = ax.set_xlabel(r'Wavelength [$\AA$]')
799+
_ = ax.set_ylabel('Flux [Arbitrary Units]')
800+
_ = ax.set_title(title)
803801
# ax.set_xlim([3500.0,10000.0])
804802
# ax.set_ylim([-400.0,500.0])
805803
# fig.savefig(base+'.zoom.png')
@@ -1515,47 +1513,44 @@ def template_input(inputfile, dumpfile, flux=False, verbose=False):
15151513
for k in range(nplots):
15161514
istart = k*nfluxes
15171515
iend = min(istart+nfluxes, nspectra) - 1
1518-
fig = plt.figure(dpi=100)
1519-
ax = fig.add_subplot(111)
1516+
fig, ax = plt.subplots(1, 1, figsize=_default_figsize, dpi=100)
15201517
for l in range(istart, iend+1):
15211518
_ = ax.plot(10.0**pcaflux['newloglam'],
15221519
pcaflux['newflux'][l, :] + separation*(l % nfluxes),
15231520
colorvec[l % len(colorvec)]+'-',
15241521
linewidth=1)
1525-
ax.set_xlabel(r'Wavelength [$\AA$]')
1526-
ax.set_ylabel(r'Flux [$\mathsf{10^{-17} erg\, cm^{-2} s^{-1} \AA^{-1}}$] + Constant')
1527-
ax.set_title('Input Spectra {0:04d}-{1:04d}'.format(istart+1, iend+1))
1528-
ax.set_ylim(pcaflux['newflux'][istart, :].min(), pcaflux['newflux'][iend-1, :].max()+separation*(nfluxes-1))
1522+
_ = ax.set_xlabel(r'Wavelength [$\AA$]')
1523+
_ = ax.set_ylabel(r'Flux [$\mathsf{10^{-17} erg\, cm^{-2} s^{-1} \AA^{-1}}$] + Constant')
1524+
_ = ax.set_title('Input Spectra {0:04d}-{1:04d}'.format(istart+1, iend+1))
1525+
_ = ax.set_ylim(pcaflux['newflux'][istart, :].min(), pcaflux['newflux'][iend-1, :].max()+separation*(nfluxes-1))
15291526
fig.savefig('{0}.flux.{1:04d}-{2:04d}.png'.format(outfile, istart+1, iend+1))
15301527
plt.close(fig)
15311528
#
15321529
# Missing data diagnostic.
15331530
#
1534-
fig = plt.figure(dpi=100)
1535-
ax = fig.add_subplot(111)
1531+
fig, ax = plt.subplots(1, 1, figsize=_default_figsize, dpi=100)
15361532
_ = ax.plot(10.0**pcaflux['newloglam'], (pcaflux['newivar'] == 0).sum(0)/float(nspectra), 'k-')
1537-
ax.set_xlabel(r'Wavelength [$\AA$]')
1538-
ax.set_ylabel('Fraction of spectra with missing data')
1539-
ax.set_title('Missing Data')
1540-
ax.grid(True)
1533+
_ = ax.set_xlabel(r'Wavelength [$\AA$]')
1534+
_ = ax.set_ylabel('Fraction of spectra with missing data')
1535+
_ = ax.set_title('Missing Data')
1536+
_ = ax.grid(True)
15411537
fig.savefig(outfile+'.missing.png')
15421538
plt.close(fig)
15431539
#
15441540
# usemask diagnostic
15451541
#
15461542
if 'usemask' in pcaflux:
1547-
fig = plt.figure(dpi=100)
1548-
ax = fig.add_subplot(111)
1543+
fig, ax = plt.subplots(1, 1, figsize=_default_figsize, dpi=100)
15491544
_ = ax.semilogy(10.0**pcaflux['newloglam'][pcaflux['usemask'] > 0],
15501545
pcaflux['usemask'][pcaflux['usemask'] > 0], 'k-',
15511546
10.0**pcaflux['newloglam'],
15521547
np.zeros(pcaflux['newloglam'].shape,
15531548
dtype=pcaflux['newloglam'].dtype) + metadata['minuse'],
15541549
'k--')
1555-
ax.set_xlabel(r'Wavelength [$\AA$]')
1556-
ax.set_ylabel('Usemask')
1557-
ax.set_title('UseMask')
1558-
ax.grid(True)
1550+
_ = ax.set_xlabel(r'Wavelength [$\AA$]')
1551+
_ = ax.set_ylabel('Usemask')
1552+
_ = ax.set_title('UseMask')
1553+
_ = ax.grid(True)
15591554
fig.savefig(outfile+'.usemask.png')
15601555
plt.close(fig)
15611556
#
@@ -1565,36 +1560,34 @@ def template_input(inputfile, dumpfile, flux=False, verbose=False):
15651560
aratio10 = pcaflux['acoeff'][:, 1]/pcaflux['acoeff'][:, 0]
15661561
aratio20 = pcaflux['acoeff'][:, 2]/pcaflux['acoeff'][:, 0]
15671562
aratio30 = pcaflux['acoeff'][:, 3]/pcaflux['acoeff'][:, 0]
1568-
fig = plt.figure(dpi=100)
1569-
ax = fig.add_subplot(111)
1563+
fig, ax = plt.subplots(1, 1, figsize=_default_figsize, dpi=100)
15701564
_ = ax.plot(aratio10, aratio20, marker='None', linestyle='None')
15711565
for k in range(len(aratio10)):
15721566
_ = ax.text(aratio10[k], aratio20[k],
15731567
'{0:04d}-{1:04d}'.format(slist.plate[k], slist.fiberid[k]),
15741568
horizontalalignment='center', verticalalignment='center',
15751569
color=colorvec[k % len(colorvec)],
15761570
fontproperties=smallfont)
1577-
# ax.set_xlim([aratio10.min(), aratio10.max])
1578-
# ax.set_xlim([aratio20.min(), aratio20.max])
1579-
ax.set_xlabel('Eigenvalue Ratio, $a_1/a_0$')
1580-
ax.set_ylabel('Eigenvalue Ratio, $a_2/a_0$')
1581-
ax.set_title('Eigenvalue Ratios')
1571+
# _ = ax.set_xlim([aratio10.min(), aratio10.max])
1572+
# _ = ax.set_xlim([aratio20.min(), aratio20.max])
1573+
_ = ax.set_xlabel('Eigenvalue Ratio, $a_1/a_0$')
1574+
_ = ax.set_ylabel('Eigenvalue Ratio, $a_2/a_0$')
1575+
_ = ax.set_title('Eigenvalue Ratios')
15821576
fig.savefig(outfile+'.a2_v_a1.png')
15831577
plt.close(fig)
1584-
fig = plt.figure(dpi=100)
1585-
ax = fig.add_subplot(111)
1578+
fig, ax = plt.subplots(1, 1, figsize=_default_figsize, dpi=100)
15861579
_ = ax.plot(aratio20, aratio30, marker='None', linestyle='None')
15871580
for k in range(len(aratio10)):
15881581
_ = ax.text(aratio20[k], aratio30[k],
15891582
'{0:04d}-{1:04d}'.format(slist.plate[k], slist.fiberid[k]),
15901583
horizontalalignment='center', verticalalignment='center',
15911584
color=colorvec[k % len(colorvec)],
15921585
fontproperties=smallfont)
1593-
# ax.set_xlim([aratio10.min(), aratio10.max])
1594-
# ax.set_xlim([aratio20.min(), aratio20.max])
1595-
ax.set_xlabel('Eigenvalue Ratio, $a_2/a_0$')
1596-
ax.set_ylabel('Eigenvalue Ratio, $a_3/a_0$')
1597-
ax.set_title('Eigenvalue Ratios')
1586+
# _ = ax.set_xlim([aratio10.min(), aratio10.max])
1587+
# _ = ax.set_xlim([aratio20.min(), aratio20.max])
1588+
_ = ax.set_xlabel('Eigenvalue Ratio, $a_2/a_0$')
1589+
_ = ax.set_ylabel('Eigenvalue Ratio, $a_3/a_0$')
1590+
_ = ax.set_title('Eigenvalue Ratios')
15981591
fig.savefig(outfile+'.a3_v_a2.png')
15991592
plt.close(fig)
16001593
#
@@ -1862,8 +1855,7 @@ def template_star(metadata, newloglam, newflux, newivar, slist, outfile,
18621855
thesesubclassnum = np.zeros(thesesubclass.size, dtype='i4')
18631856
colorvec = ['k', 'r', 'g', 'b', 'm', 'c']
18641857
smallfont = FontProperties(size='xx-small')
1865-
fig = plt.figure(dpi=100)
1866-
ax = fig.add_subplot(111)
1858+
fig, ax = plt.subplots(1, 1, figsize=_default_figsize, dpi=100)
18671859
for isub in range(nsubclass):
18681860
ii = (thesesubclass == subclasslist[isub]).nonzero()[0]
18691861
thesesubclassnum[ii] = isub
@@ -1881,13 +1873,13 @@ def template_star(metadata, newloglam, newflux, newivar, slist, outfile,
18811873
# Plot spectra
18821874
#
18831875
plotflux = thisflux/thisflux.max()
1884-
ax.plot(10.0**newloglam, plotflux,
1885-
"{0}-".format(colorvec[isub % len(colorvec)]),
1886-
linewidth=1)
1876+
_ = ax.plot(10.0**newloglam, plotflux,
1877+
"{0}-".format(colorvec[isub % len(colorvec)]),
1878+
linewidth=1)
18871879
if isub == 0:
1888-
ax.set_xlabel(r'Wavelength [$\AA$]')
1889-
ax.set_ylabel('Flux [arbitrary units]')
1890-
ax.set_title('STAR {0}: Eigenspectra Reconstructions'.format(c))
1880+
_ = ax.set_xlabel(r'Wavelength [$\AA$]')
1881+
_ = ax.set_ylabel('Flux [arbitrary units]')
1882+
_ = ax.set_title('STAR {0}: Eigenspectra Reconstructions'.format(c))
18911883
_ = ax.text(10.0**newloglam[-1], plotflux[-1],
18921884
subclasslist[isub],
18931885
horizontalalignment='right', verticalalignment='center',
@@ -1919,7 +1911,8 @@ def template_input_main(): # pragma: no cover
19191911
#
19201912
import sys
19211913
from argparse import ArgumentParser
1922-
1914+
import matplotlib
1915+
matplotlib.use("Agg")
19231916
# Get home directory in platform-independent way
19241917
home_dir = os.path.expanduser('~')
19251918
#

0 commit comments

Comments
 (0)