示例#1
0
def plot_single_fom(rhist_fom, label, fom_label, **kwargs):
    """Make a plot of a single FOM distribution

    Parameters
    ----------
    rhist_fom : cafplot.RHist1D
        Histogram containing FOM.
    label : str
        Plot label.
    fom_label : str
        Name of the Figure of Merit.
    kwargs : dict
        Parameters that will be passed to `plot_rhist1d` function.

    Returns
    -------
    f : matplotlib.Figure
        Matplotlib figure.
    ax : matplotlib.Axes
        Matplotlib Axes.
    """
    f, ax = plt.subplots()

    plot_rhist1d(ax, rhist_fom, None, histtype='step', **kwargs)
    decorate_fom_axes(ax, label)

    ax.set_title('%s for %s' % (fom_label.capitalize(), label.capitalize()))
    ax.set_ylabel(fom_label.capitalize())

    return f, ax
示例#2
0
文件: hist.py 项目: wswxyq/lstm_ee
def plot_hist_base(
    list_of_data_weight_label_color, key, spec, ratio_plot_type, stat_err,
    log = False
):
    """Plot multiple energy histograms"""

    if ratio_plot_type is not None:
        f, ax, axr = make_figure_with_ratio()
    else:
        f, ax = plt.subplots()

    if log:
        ax.set_yscale('log')

    list_of_rhist_color = []

    for (data,weights,label,color) in list_of_data_weight_label_color:
        rhist = RHist1D.from_data(data[key], spec.bins_x, weights)

        centers = (rhist.bins_x[1:] + rhist.bins_x[:-1]) / 2
        mean = np.average(centers, weights = rhist.hist)

        plot_rhist1d(
            ax, rhist,
            histtype = 'step',
            marker    = None,
            linestyle = '-',
            linewidth = 2,
            label     = "%s. MEAN = %.3e" % (label, mean),
            color     = color,
        )

        if stat_err:
            plot_rhist1d_error(
                ax, rhist, err_type = 'bar', color = color, linewidth = 2,
                alpha = 0.8
            )

        list_of_rhist_color.append((rhist, color))

    spec.decorate(ax, ratio_plot_type)

    if not log:
        remove_bottom_margin(ax)

    ax.legend()

    if ratio_plot_type is not None:
        plot_rhist1d_ratios(
            axr,
            [rhist_color[0] for rhist_color in list_of_rhist_color],
            [rhist_color[1] for rhist_color in list_of_rhist_color],
            err_kwargs = { 'err_type' : 'bar' if stat_err else None },
        )
        spec.decorate_ratio(axr, ratio_plot_type)

    return f, ax
示例#3
0
def plot_fom_base(ax, rhist, stats, label, pos, color, spec):
    """
    Plot relative energy resolution histogram and draw textbox with stat info.
    """

    plot_rhist1d(ax, rhist, histtype='step', label=label, color=color)
    plot_gauss_fit(ax, rhist.bins_x, stats, color=color)

    add_stats_text(ax, stats, label, pos, color=color)
    spec.decorate(ax)
示例#4
0
def plot_overlayed_foms(fom_dict, foms_to_overlay, labels, plotdir, ext):
    """Make and save separate plots of FOMs.

    Multiple plots will be made -- one for each target.
    Multiple FOMs will be overlayed on a single plot -- one for each element
    in `foms_to_overlay`.

    Parameters
    ----------
    fom_dict : dict
        Dictionary of FOMs where keys are names of the FOM and values are
        lists of cafplot.RHist1D containing FOM for different targets.
    foms_to_overlay : list of str
        List of FOM names that will be overlayed on a single plot.
    labels : list of str
        List of target names. Each list in the `fom_dict` should have the
        same length as `labels`.
    plotdir : str
        Directory where plots will be saved.
    ext : str or list of str
        Extension of the plots. If list then the plots will be saved in
        multiple formats.
    """

    for pred_idx, x_label in enumerate(labels):
        f, ax = plt.subplots()

        for fom_idx, fom_label in enumerate(foms_to_overlay):
            rhist_fom = fom_dict[fom_label][pred_idx]

            rhist_fom.scale(1 / np.max(rhist_fom.hist))
            plot_rhist1d(ax,
                         rhist_fom,
                         fom_label.capitalize(),
                         histtype='step',
                         color='C%d' % (fom_idx, ))

        decorate_fom_axes(ax, x_label)

        ax.set_ylabel('FOMs')
        ax.set_title('Normalized FOMs')
        ax.legend()

        fname = 'overlayed_foms_%s' % (x_label, )
        save_fig(f, os.path.join(plotdir, fname), ext)
        plt.close(f)
示例#5
0
def plot_counts(counts, labels, plotdir, ext):
    # pylint: disable=missing-function-docstring
    norm = np.sum(counts)

    f, ax = plt.subplots()

    rhist = RHist1D(np.arange(len(labels) + 1), counts)
    rhist.scale(100 / norm)

    plot_rhist1d(ax, rhist, label = "", histtype = 'bar', color = 'tab:blue')

    ax.set_xticks([ i + 0.5 for i in range(len(labels))])
    ax.set_xticklabels(labels)

    ax.set_ylabel("Fraction [%]")
    ax.set_title("Distribution of events per category")

    save_fig(f, os.path.join(plotdir, "sample_distribution_test"), ext)
示例#6
0
def plot_single_distribution(
    ax, truth_idx, truth, preds, weights, bins, labels, **kwargs
):
    """Plot distribution of predicted PID values for a single true component.

    Parameters
    ----------
    ax : matplotlib.Axes
        Axes where histogram will be plotted.
    truth_idx : int
        Value of the true component to be plotted.
    truth : ndarray, shape (N_SAMPLES,)
        Array of true targets.
    preds : ndarray, shape (N_SAMPLES,)
        Array of predicted target scores.
    weights : ndarray, shape (N_SAMPLES,)
        Sample weights.
    bins : int
        Number of bins of the hist plots.
    labels : list of str, len(N_TARGETS)
        List of labels for each target.
    kwargs : dict
        Parameters that will be passed to the histogram plot functions.

    See Also
    --------
    plot_rhist1d
    plot_rhist1d_error
    """

    truth_mask = (truth == truth_idx)

    rhist = RHist1D.from_data(
        preds[truth_mask], weights = weights[truth_mask],
        bins = bins, range = (0, 1)
    )

    plot_rhist1d(ax, rhist, labels[truth_idx], histtype = 'step', **kwargs)
    plot_rhist1d_error(
        ax, rhist, err_type = 'bar', err = 'normal', sigma = 1, **kwargs
    )
示例#7
0
def plot_energy(data, weights, name, spec, log_scale=False):
    """Plot single energy distribution."""
    f, ax = plt.subplots()
    if log_scale:
        ax.set_yscale('log')

    rhist = RHist1D.from_data(data, spec.bins_x, weights)

    plot_rhist1d(
        ax,
        rhist,
        histtype='step',
        linewidth=2,
        color='C0',
        label="True %s. Mean: %.2e" %
        (name, np.average(data, weights=weights)),
    )
    plot_rhist1d_error(ax, rhist, err_type='bar', color='C0', linewidth=2)

    spec.decorate(ax)
    ax.legend()
    remove_bottom_margin(ax)

    return f, ax, rhist
示例#8
0
where FILE is a file containing Spectrum to be plotted.
The Spectrum is expected to be found in the PATH directory of the FILE.
"""

import sys
import matplotlib.pyplot as plt

from cafplot import load
from cafplot.plot import plot_rhist1d, plot_rhist1d_error, adjust_axes_to_hist

root_file = load(sys.argv[1])
spectrum = root_file.get_spectrum(sys.argv[2])

pot = 9e20
rhist = spectrum.rhist(pot=pot)

f, ax = plt.subplots()

plot_rhist1d(ax, rhist, 'Histogram', 'step', color='C0')
plot_rhist1d_error(ax, rhist, color='C0', err_type='bar')

# Fit axes ranges to the histogram
adjust_axes_to_hist(ax, rhist)

ax.set_xlabel(sys.argv[2])
ax.set_ylabel('Events')

ax.legend()

plt.show()