Skip to content

Commit

Permalink
remove most uses of matplotlib.pyplot.tight_layout; use figure(layout…
Browse files Browse the repository at this point in the history
…="constrained") instead

cla module still needs to be updated
  • Loading branch information
twmacro committed Oct 1, 2023
1 parent 8e621e1 commit 376bb0e
Show file tree
Hide file tree
Showing 16 changed files with 80 additions and 103 deletions.
5 changes: 2 additions & 3 deletions pyyeti/cb.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ def cbtf(m, b, k, a, freq, bset, save=None):
>>> a = T @ tf.a
>>> d = T @ tf.d
>>> fig = plt.figure('Example')
>>> fig.clf()
>>> fig = plt.figure('Example', clear=True,
... layout='constrained')
>>> ax = plt.subplot(211)
>>> lines = ax.plot(outfreq, np.abs(tf.frc).T, label='Force')
>>> lines += ax.plot(outfreq, np.abs(a).T)
Expand All @@ -199,7 +199,6 @@ def cbtf(m, b, k, a, freq, bset, save=None):
... loc='best')
>>> _ = ax.set_title('Phase')
>>> _ = ax.set_xlabel('Freq (Hz)')
>>> plt.tight_layout()
"""
freq = np.atleast_1d(freq).ravel()
Omega = 2 * math.pi * freq
Expand Down
53 changes: 25 additions & 28 deletions pyyeti/dsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ def resample(data, p, q, *, axis=-1, beta=14, pts=10, t=None, getfir=False):
>>> n = len(data)
>>> x = np.arange(n)
>>> upx = np.arange(n*p)/p
>>> _ = plt.figure('Example', figsize=(10, 8), clear=True)
>>> _ = plt.figure('Example', figsize=(10, 8), clear=True,
... layout='constrained')
>>> _ = plt.subplot(211)
>>> _ = plt.plot(x, data, 'o-', label='Original')
>>> res = {}
Expand Down Expand Up @@ -172,7 +173,6 @@ def resample(data, p, q, *, axis=-1, beta=14, pts=10, t=None, getfir=False):
>>> _ = plt.legend(loc='best')
>>> _ = plt.title('FFT Mag.')
>>> _ = plt.xlabel('Frequency - fraction of original sample rate')
>>> _ = plt.tight_layout()
>>> np.allclose(up2, upx)
True
>>> np.allclose(res[5][::p], data) # original data still here
Expand All @@ -190,7 +190,8 @@ def resample(data, p, q, *, axis=-1, beta=14, pts=10, t=None, getfir=False):
>>> data = rng.normal(size=n)
>>> x = np.arange(n)
>>> dndata, dnx = dsp.resample(data, p, q, t=x)
>>> fig = plt.figure('Example 2', clear=True)
>>> fig = plt.figure('Example 2', clear=True,
... layout='constrained')
>>> _ = plt.subplot(211)
>>> _ = plt.plot(x, data, 'o-', label='Original', alpha=0.3)
>>> _ = plt.plot(dnx, dndata, label='Resample', lw=2)
Expand All @@ -214,7 +215,6 @@ def resample(data, p, q, *, axis=-1, beta=14, pts=10, t=None, getfir=False):
>>> xlbl = 'Frequency - fraction of original sample rate'
>>> _ = plt.xlabel(xlbl)
>>> _ = plt.xlim(-0.01, 0.13)
>>> _ = plt.tight_layout()
"""
data = np.atleast_1d(data)
ln = data.shape[axis]
Expand Down Expand Up @@ -761,7 +761,8 @@ def despike(
>>> import matplotlib.pyplot as plt
>>> np.set_printoptions(linewidth=65)
>>> x = [100, 2, 3, -4, 25, -6, 6, 3, -2, 4, -2, -100]
>>> _ = plt.figure('Example', figsize=(8, 11), clear=True)
>>> _ = plt.figure('Example', figsize=(8, 11), clear=True,
... layout='constrained')
>>> for i in range(5):
... s = dsp.despike(x, n=9, sigma=2, maxiter=1,
... threshold_sigma=0.1,
Expand All @@ -772,7 +773,6 @@ def despike(
... _ = plt.plot(s.lolim, 'k--')
... _ = plt.title(f'Iteration {i+1}')
... x = s.x
>>> plt.tight_layout()
>>> s.x
array([ 2, 3, 6, 3, -2, 4, -2])
Expand Down Expand Up @@ -2085,7 +2085,8 @@ def windowends(sig, portion=0.01, ends="front", axis=-1):
:context: close-figs
>>> import matplotlib.pyplot as plt
>>> _ = plt.figure('Example', figsize=[8, 3], clear=True)
>>> _ = plt.figure('Example', figsize=[8, 3], clear=True,
... layout='constrained')
>>> sig = np.ones(100)
>>> wesig = dsp.windowends(sig, 5, ends='both')
>>> _ = plt.plot(sig, label='Original')
Expand Down Expand Up @@ -2253,7 +2254,7 @@ def waterfall(
... slicefunc=dsp.windowends,
... sliceargs=[.02],
... slicekwargs=dict(ends='front'))
>>> _ = plt.figure('Example', clear=True)
>>> _ = plt.figure('Example', clear=True, layout='constrained')
>>> cs = plt.contour(t, f, mp, 40, cmap=cm.plasma_r)
>>> # This doesn't work in matplotlib 3.5.0:
>>> # cbar = plt.colorbar()
Expand All @@ -2264,7 +2265,7 @@ def waterfall(
... vmin=cs.cvalues.min(), vmax=cs.cvalues.max()
... )
>>> sm = plt.cm.ScalarMappable(norm=norm, cmap=cs.cmap)
>>> cb = plt.colorbar(sm) # , ticks=cs.levels)
>>> cb = plt.colorbar(sm, ax=plt.gca()) # , ticks=cs.levels)
>>> #
>>> _ = plt.xlabel('Time (s)')
>>> _ = plt.ylabel('Frequency (Hz)')
Expand All @@ -2276,7 +2277,8 @@ def waterfall(
Also show results on a 3D surface plot:
>>> fig = plt.figure("Example 2", clear=True)
>>> fig = plt.figure("Example 2", clear=True,
... layout='constrained')
>>> ax = fig.add_subplot(projection="3d")
>>> x, y = np.meshgrid(t, f)
>>> surf = ax.plot_surface(x, y, mp, rstride=1, cstride=1,
Expand Down Expand Up @@ -2510,7 +2512,8 @@ def calcenv(
>>> from pyyeti import dsp
>>> x = np.arange(1.0, 31.0, 1.0)
>>> y = np.cos(x)
>>> fig = plt.figure('Example', figsize=[10, 8], clear=True)
>>> fig = plt.figure('Example', figsize=[10, 8], clear=True,
... layout='constrained')
>>>
>>> ax = plt.subplot(411)
>>> env = dsp.calcenv(x, y, base=None, makeplot='add')
Expand All @@ -2536,7 +2539,6 @@ def calcenv(
>>> env = dsp.calcenv(x, y, method='min', makeplot='add')
>>> _ = plt.title('method="min"')
>>> ax.legend().set_visible(False)
>>> fig.subplots_adjust(right=0.7)
"""
x, y = np.atleast_1d(x, y)
if np.any(np.diff(x) <= 0):
Expand Down Expand Up @@ -2647,7 +2649,7 @@ def fdscale(y, sr, scale, axis=-1):
... [9., 1.0],
... [100., 1.0]])
>>> sig_scaled = dsp.fdscale(sig, 1/t[1], scale)
>>> _ = plt.figure('Example', clear=True)
>>> _ = plt.figure('Example', clear=True, layout='constrained')
>>> _ = plt.subplot(211)
>>> _ = plt.plot(f, sig)
>>> _ = plt.title('Sine Sweep vs Frequency')
Expand All @@ -2661,7 +2663,6 @@ def fdscale(y, sr, scale, axis=-1):
>>> _ = plt.xlabel('Frequency (Hz)')
>>> _ = plt.xlim([f[0], f[-1]])
>>> _ = plt.grid(True)
>>> _ = plt.tight_layout()
"""
y = np.atleast_1d(y)
n = y.shape[axis]
Expand Down Expand Up @@ -2837,24 +2838,20 @@ def fftfilt(
>>> sr = 1/h
>>> nyq = sr/2
>>> _ = plt.figure('Example', clear=True)
>>> _ = plt.figure('Example 2', clear=True)
>>> _ = plt.figure('Ex1', clear=True, layout='constrained')
>>> _ = plt.figure('Ex2', clear=True, layout='constrained')
>>> for j, (w, pz, yj) in enumerate(((7, None, y1),
... ([7, 18], None, y2),
... ([18, 45], None, y3),
... (45, False, y4))):
... _ = plt.figure('Example')
... _ = plt.figure('Ex1')
... _ = plt.subplot(4, 1, j+1)
... yf = dsp.fftfilt(y, w, pass_zero=pz, nyq=nyq,
... makeplot='add')[0]
... _ = plt.xlim(0, 75)
... _ = plt.figure('Example 2')
... _ = plt.figure('Ex2')
... _ = plt.subplot(4, 1, j+1)
... _ = plt.plot(t, yj, t, yf)
>>> _ = plt.figure('Example')
>>> _ = plt.tight_layout()
>>> _ = plt.figure('Example 2')
>>> _ = plt.tight_layout()
"""
# main routine:
sig, w = np.atleast_1d(sig, w)
Expand Down Expand Up @@ -3057,7 +3054,7 @@ def fftcoef(
>>> x = rng.normal(size=n)
>>> t = np.arange(n)
>>> mag, phase, frq = dsp.fftcoef(x, 1.0)
>>> _ = plt.figure('Example', clear=True)
>>> _ = plt.figure('Example', clear=True, layout='constrained')
>>> _ = plt.subplot(211)
>>> _ = plt.plot(frq, mag)
>>> _ = plt.ylabel('Magnitude')
Expand All @@ -3082,7 +3079,8 @@ def fftcoef(
>>> for k, (a, b, f) in enumerate(zip(A, B, frq)):
... x3 = x3 + a*np.cos(k*w*t2) + b*np.sin(k*w*t2)
>>>
>>> _ = plt.figure('Example 2', clear=True)
>>> _ = plt.figure('Example 2', clear=True,
... layout='constrained')
>>> _ = plt.plot(t, x, 'o', label='Original')
>>> _ = plt.plot(t2, x2, label='FFT fit w/ Mag & Phase')
>>> _ = plt.plot(t2, x3, '--', label='FFT fit w/ A & B')
Expand Down Expand Up @@ -3245,7 +3243,7 @@ def fftmap(
... vmin=cs.cvalues.min(), vmax=cs.cvalues.max()
... )
>>> sm = plt.cm.ScalarMappable(norm=norm, cmap=cs.cmap)
>>> cb = plt.colorbar(sm) # , ticks=cs.levels)
>>> cb = plt.colorbar(sm, ax=plt.gca()) # , ticks=cs.levels)
>>> #
>>> _ = plt.xlabel('Time (s)')
>>> _ = plt.ylabel('Frequency (Hz)')
Expand Down Expand Up @@ -3443,7 +3441,8 @@ def transmissibility(
>>> tr = dsp.transmissibility(
... in_acce, out_acce, sr, getmap=True)
>>>
>>> fig = plt.figure('Example', figsize=(8, 11), clear=True)
>>> fig = plt.figure('Example', figsize=(8, 11), clear=True,
... layout='tight')
>>>
>>> # use GridSpec to make a nice layout with colorbars:
>>> gs = gridspec.GridSpec(5, 2, width_ratios=[30, 1])
Expand Down Expand Up @@ -3527,8 +3526,6 @@ def transmissibility(
>>> cb = plt.colorbar(sm, cax=ax) # , ticks=c.levels)
>>>
>>> _ = ax.set_title("TR Phase (deg)")
>>>
>>> fig.tight_layout()
As an aside and for fun, compare the actual root-mean-square
response to the Miles' equation estimate. Miles' should be a
Expand Down
9 changes: 5 additions & 4 deletions pyyeti/era.py
Original file line number Diff line number Diff line change
Expand Up @@ -1116,7 +1116,9 @@ def _plot_era(self):

# plot each input in its own window
for j in range(self.n_inputs):
fig = plt.figure(f"{self.figure_label}, input {j}", clear=True)
fig = plt.figure(
f"{self.figure_label}, input {j}", clear=True, layout="constrained"
)

if self.FFT:
ax1 = fig.add_subplot(211)
Expand Down Expand Up @@ -1192,7 +1194,6 @@ def _plot_era(self):
ax2.set_ylabel("Magnitude")
ax2.set_title("Magnitude of Frequency Responses of Data")

fig.tight_layout()
fig.canvas.draw()
plt.show()

Expand Down Expand Up @@ -1580,7 +1581,8 @@ def NExT(
>>> t_irf = t[1 : lag_stop + 1]
>>> irf = era.NExT(sol.a, sr, lag_stop=lag_stop)
>>>
>>> fig = plt.figure("corr comp", clear=True, figsize=(6.4, 6.4))
>>> fig = plt.figure("corr comp", clear=True, figsize=(6.4, 6.4),
... layout='constrained')
>>> ax = fig.subplots(4, 1)
>>>
>>> _ = ax[0].plot(t, sol.a.T)
Expand All @@ -1595,7 +1597,6 @@ def NExT(
... _ = ax[ref + 1].set_title(f"IRFs with reference channel {ref}")
... _ = ax[ref + 1].set_ylabel("X-corr IRFs")
>>> _ = ax[3].set_xlabel("Time (s)")
>>> fig.tight_layout()
.. plot::
:context: close-figs
Expand Down
10 changes: 4 additions & 6 deletions pyyeti/fdepsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,8 +470,8 @@ def fftroll(sig, sr, ppc, frq):
... spec, ppc=10, fstart=20, fstop=50, df=1 / TF,
... winends=dict(portion=10), gettime=True)
>>>
>>> fig = plt.figure('Example', figsize=[9, 6])
>>> fig.clf()
>>> fig = plt.figure('Example', figsize=[9, 6], clear=True,
... layout='constrained')
>>> _ = plt.subplot(211)
>>> _ = plt.plot(t, sig)
>>> _ = plt.title(r'Input Signal - Specification Level = '
Expand Down Expand Up @@ -507,16 +507,14 @@ def fftroll(sig, sr, ppc, frq):
>>> _ = plt.legend(loc='upper left',
... bbox_to_anchor=(1.02, 1.),
... borderaxespad=0.)
>>> plt.tight_layout()
>>> fig.subplots_adjust(right=0.78)
.. plot::
:context: close-figs
Compare to theoretical bin counts @ 30 Hz:
>>> _ = plt.figure('Example 2')
>>> plt.clf()
>>> _ = plt.figure('Example 2', clear=True,
... layout='constrained')
>>> Frq = freq[np.searchsorted(freq, 30)]
>>> _ = plt.semilogy(fde.binamps.loc[Frq]**2,
... fde.count.loc[Frq],
Expand Down
18 changes: 7 additions & 11 deletions pyyeti/frclim.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ def calcAM(S, freq):
>>> zeta_ff = C_ff[1, 1] / 2 / omega_ff[1]
>>>
>>> freq = np.geomspace(0.5, 100.0, 500)
>>> fig = plt.figure("apparent mass", clear=True)
>>> fig = plt.figure("apparent mass", clear=True,
... layout='constrained')
>>> ax = fig.subplots(1, 1)
>>>
>>> fx_frqs = []
Expand Down Expand Up @@ -180,8 +181,6 @@ def calcAM(S, freq):
... "\n (free-free)"
... )
>>> _ = ax.text(frq_ff[1], 2.0, label, va="bottom", ha="left")
>>>
>>> fig.tight_layout()
"""

lf = len(freq)
Expand Down Expand Up @@ -688,8 +687,7 @@ def ntfl(Source, Load, As, freq):
5. Plot comparisons:
>>> import matplotlib.pyplot as plt
>>> _ = plt.figure('Example')
>>> plt.clf()
>>> _ = plt.figure('Example', clear=True, layout='constrained')
>>> _ = plt.subplot(211)
>>> _ = plt.semilogy(freq, abs(A_coupled),
... label='Coupled')
Expand All @@ -706,15 +704,14 @@ def ntfl(Source, Load, As, freq):
>>> _ = plt.title('Interface Force')
>>> _ = plt.xlabel('Frequency (Hz)')
>>> _ = plt.legend(loc='best')
>>> plt.tight_layout()
.. plot::
:context: close-figs
6. Plot apparent masses:
>>> _ = plt.figure('Example 2')
>>> plt.clf()
>>> _ = plt.figure('Example 2', clear=True,
... layout='constrained')
>>> _ = plt.semilogy(freq, abs(r.TAM[0, :, 0]),
... label='Total App. Mass')
>>> _ = plt.semilogy(freq, abs(r.SAM[0, :, 0]),
Expand All @@ -731,8 +728,8 @@ def ntfl(Source, Load, As, freq):
7. Plot accelerations and
8. Plot force limit factor:
>>> _ = plt.figure('Example 3')
>>> plt.clf()
>>> _ = plt.figure('Example 3', clear=True,
... layout='constrained')
>>> _ = plt.subplot(211)
>>> _ = plt.semilogy(freq, abs(As).T,
... label='Free-Acce')
Expand All @@ -746,7 +743,6 @@ def ntfl(Source, Load, As, freq):
>>> _ = plt.title('NT Response Ratio: '
... 'R = Coupled Acce / Free-Acce')
>>> _ = plt.xlabel('Frequency (Hz)')
>>> plt.tight_layout()
"""
# Calculate apparent masses:
if isinstance(Source, (list, tuple)):
Expand Down
1 change: 0 additions & 1 deletion pyyeti/nastran/bulk.py
Original file line number Diff line number Diff line change
Expand Up @@ -3921,7 +3921,6 @@ def _plot_rspline(

ytools.axis_equal_3d(ax)
ax.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0))
ax.get_figure().tight_layout()


def wtrspline_rings(
Expand Down
7 changes: 3 additions & 4 deletions pyyeti/ode/_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def get_su_coef(m, b, k, h, rbmodes=None, rfmodes=None):
else:
wo2 = k / m
C = (b / m) / 2
w2 = wo2 - C ** 2
w2 = wo2 - C**2

if rbmodes is None:
pvrb = (wo2 < 0.005).astype(int)
Expand Down Expand Up @@ -1064,8 +1064,8 @@ def solvepsd(fs, forcepsd, t_frc, freq, drmlist, rbduf=1.0, elduf=1.0, **kwargs)
Plot the four accelerations PSDs:
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure('Example', figsize=[8, 8])
>>> fig.clf()
>>> fig = plt.figure('Example', figsize=[8, 8], clear=True,
... layout='constrained')
>>> labels = ['Rigid-body', 'Underdamped',
... 'Critically Damped', 'Overdamped']
>>> for j, name in zip(range(4), labels):
Expand All @@ -1074,7 +1074,6 @@ def solvepsd(fs, forcepsd, t_frc, freq, drmlist, rbduf=1.0, elduf=1.0, **kwargs)
... _ = plt.title(name)
... _ = plt.ylabel(r'Accel PSD ($g^2$/Hz)')
... _ = plt.xlabel('Frequency (Hz)')
>>> fig.tight_layout()
"""
ndrms = len(drmlist)
forcepsd, t_frc = np.atleast_2d(forcepsd, t_frc)
Expand Down
Loading

0 comments on commit 376bb0e

Please sign in to comment.