|
| 1 | +import matplotlib.pyplot as plt |
| 2 | +from mpl_toolkits.axes_grid1 import make_axes_locatable |
| 3 | +from matplotlib.widgets import SpanSelector |
| 4 | +from matplotlib.colors import LogNorm |
| 5 | +import numpy as np |
| 6 | +import h5py |
| 7 | + |
| 8 | +def plot_all_chan_spectrum(spectrum, bins, *, ax=None, **kwargs): |
| 9 | + |
| 10 | + def integrate_to_angles(spectrum, bins, lo, hi): |
| 11 | + lo_ind, hi_ind = bins.searchsorted([lo, hi]) |
| 12 | + return spectrum[lo_ind:hi_ind].sum(axis=0) |
| 13 | + |
| 14 | + if ax is None: |
| 15 | + fig, ax = plt.subplots(figsize=(13.5, 9.5)) |
| 16 | + else: |
| 17 | + fig = ax.figure |
| 18 | + |
| 19 | + div = make_axes_locatable(ax) |
| 20 | + ax_r = div.append_axes('right', 2, pad=0.1, sharey=ax) |
| 21 | + ax_t = div.append_axes('top', 2, pad=0.1, sharex=ax) |
| 22 | + |
| 23 | + ax_r.yaxis.tick_right() |
| 24 | + ax_r.yaxis.set_label_position("right") |
| 25 | + ax_t.xaxis.tick_top() |
| 26 | + ax_t.xaxis.set_label_position("top") |
| 27 | + |
| 28 | + im = ax.imshow(spectrum, origin='lower', aspect='auto', |
| 29 | + extent=(-.5, 383.5, |
| 30 | + bins[0], bins[-1]), |
| 31 | + norm=LogNorm()) |
| 32 | + |
| 33 | + e_line, = ax_r.plot(spectrum.sum(axis=1), bins[:-1] + np.diff(bins)) |
| 34 | + p_line, = ax_t.plot(spectrum.sum(axis=0)) |
| 35 | + label = ax_t.annotate('[0, 70] kEv', (0, 1), (10, -10), |
| 36 | + xycoords='axes fraction', |
| 37 | + textcoords='offset pixels', |
| 38 | + va='top', ha='left') |
| 39 | + |
| 40 | + def update(lo, hi): |
| 41 | + p_data = integrate_to_angles(spectrum, bins, lo, hi) |
| 42 | + p_line.set_ydata(p_data) |
| 43 | + ax_t.relim() |
| 44 | + ax_t.autoscale(axis='y') |
| 45 | + |
| 46 | + label.set_text(f'[{lo:.1f}, {hi:.1f}] keV') |
| 47 | + fig.canvas.draw_idle() |
| 48 | + |
| 49 | + span = SpanSelector(ax_r, update, 'vertical', useblit=True, |
| 50 | + rectprops={'alpha': .5, 'facecolor': 'red'}, |
| 51 | + span_stays=True) |
| 52 | + |
| 53 | + ax.set_xlabel('channel [#]') |
| 54 | + ax.set_ylabel('E [keV]') |
| 55 | + |
| 56 | + ax_t.set_xlabel('channel [#]') |
| 57 | + ax_t.set_ylabel('total counts') |
| 58 | + |
| 59 | + ax_r.set_ylabel('E [keV]') |
| 60 | + ax_r.set_xlabel('total counts') |
| 61 | + ax.set_xlim(-.5, 383.5) |
| 62 | + ax.set_ylim(bins[0], bins[-1]) |
| 63 | + ax_r.set_xlim(xmin=0) |
| 64 | + |
| 65 | + return spectrum, bins, {'center': {'ax': ax, 'im': im}, |
| 66 | + 'top': {'ax': ax_t, 'p_line': p_line}, |
| 67 | + 'right': {'ax': ax_r, 'e_line': e_line, |
| 68 | + 'span': span}} |
| 69 | + |
| 70 | + |
| 71 | +with h5py.File('germ.h5', 'r') as fin: |
| 72 | + spectrum = fin['spectrum'][:] |
| 73 | + bins = fin['bins'][:] |
| 74 | + |
| 75 | +plot_all_chan_spectrum(spectrum, bins) |
| 76 | +plt.show() |
0 commit comments