Beispiel #1
0
def plot_histogram(axes: mpl.axes.Axes, hist, popt, bin_edges: np.ndarray,
                   axis: str):
    """ plots the histogram of one of the axis projections

    Plot the projection of histogram of hits. The plot is plotted vertically
    if the axis label is given as 'y'

    Parameters
    ----------
    axes : mpl.axes.Axes
        the axes to plot the histogram into. The plot will be vertical if the
        axis is specified to be 'y'
    hist : np.ndarray
        the histogramd hits
    popt : np.ndarray
        the parameters for the Gaussian that to be plotted over the hist
    bin_edges : np.ndarray
        the edges of the bins used for the histogram
    axis : str
        the axis on for which the results should be plotted (either 'x'
        or 'y'). Plots vertically if 'y' is specified.
    """
    bin_centers = (bin_edges[1:] + bin_edges[:-1])/2
    if axis == 'x':
        axes.set_xlim([bin_edges[0], bin_edges[-1]])
        axes.hist(bin_edges[:-1], bin_edges, weights=hist, density=True)
        axes.plot(bin_centers, norm.pdf(bin_centers, *popt))
    elif axis == 'y':
        axes.set_ylim([bin_edges[0], bin_edges[-1]])
        axes.hist(bin_edges[:-1], bin_edges, weights=hist, density=True,
                  orientation='horizontal')
        axes.plot(norm.pdf(bin_centers, *popt), bin_centers)
    else:
        raise ValueError("axis has to be either 'x' or 'y'")
def plot_histogram(data_numpy: np.ndarray,
                   xlabel: str,
                   bins: str = 40,
                   label: str = None,
                   color: str = 'grey',
                   ax: matplotlib.axes.Axes = None):
    """
    Visualizes data as a histogram
    
    Parameters:
    data_numpy (numpy.ndarray): numpy ndarray of shape Nx1
    xlabel (str): text that is displayed under the x axis
    bins (int): number of bins in the histogram (default 40)
    label (str): title of the histogram (default None)
    color (str): color of the barplot
    ax (matplotlib.axes.Axes): Axes to be used for plotting (default: create new)
    
    Returns:
    None
    """
    if ax == None:
        ax = plt.gca()
    ax.hist(data_numpy, bins=bins, color=color, label=label)
    ax.set_yticks([])
    ax.set_ylabel("Frequency")
    ax.set_xlabel(xlabel)
    ax.tick_params(left=False, bottom=False)
Beispiel #3
0
def plot_ece_samples(ax: mpl.axes.Axes,
                     ground_truth_ece: float,
                     frequentist_ece,
                     samples_posterior: np.ndarray,
                     plot_kwargs: Dict[str, Any] = {}) -> mpl.axes.Axes:
    """

    :param ax:
    :param ground_truth_ece: float
    :param frequentist_ece: float or np.ndarray

    :param samples_posterior:
    :param plot_kwargs:
    :return:
    """
    _plot_kwargs = DEFAULT_PLOT_KWARGS.copy()
    _plot_kwargs.update(plot_kwargs)
    if isinstance(frequentist_ece, float):
        ax.axvline(x=frequentist_ece,
                   label='Frequentist',
                   color='blue',
                   **_plot_kwargs)
    else:
        ax.hist(frequentist_ece,
                color='blue',
                alpha=0.7,
                label='Frequentist',
                **_plot_kwargs)
    ax.hist(samples_posterior,
            color='red',
            label='Bayesian',
            alpha=0.7,
            **_plot_kwargs)
    ax.axvline(x=ground_truth_ece,
               label='Ground truth',
               color='black',
               **_plot_kwargs)

    ax.set_xlim(0, 0.3)
    ax.set_xticks([0.0, 0.1, 0.2, 0.3])

    return ax
Beispiel #4
0
def hist1d(foreground,
           background,
           axis: matplotlib.axes.Axes,
           dataset_name: str,
           normalize=True,
           nbins: np.ndarray = np.linspace(-20, 20, 40),
           norm_ymax=10,
           log=False,
           bg_label='total IMF'):
    """Plots 1D histogram of e.g. BxGSM.
    Parameters
    ----------
    foreground (array_like): data for the TPAs.
    background (array_like): all the data for the IMF during the period of the dataset.

    Returns
    -------
    fg_hist_values, bg_hist_values, bins
    """
    foreground = foreground[~np.isnan(foreground)]
    background = background[~np.isnan(background)]

    axis.axvline(0, color="grey", lw=1, zorder=-1)
    bg_hist_values, _, _ = axis.hist(background,
                                     bins=nbins,
                                     weights=np.ones_like(background) /
                                     len(background),
                                     label=bg_label,
                                     histtype='step',
                                     zorder=0)
    fg_hist_values, bins, _ = axis.hist(foreground,
                                        bins=nbins,
                                        weights=np.ones_like(foreground) /
                                        len(foreground),
                                        label=dataset_name,
                                        histtype='step',
                                        zorder=1)
    if normalize:
        normalized_axis = axis.twinx(
        )  # instantiate a second axes that shares the same x-axis
        normalized_axis.axhline(1, ls="--", color='lightgrey', lw=1)
        masked_bg_hist_values = np.ma.masked_where(bg_hist_values == 0,
                                                   bg_hist_values)
        normalized_axis.plot((bins[1:] + bins[:-1]) / 2,
                             fg_hist_values / masked_bg_hist_values,
                             c='g',
                             label='IMF normalized',
                             zorder=2)
        normalized_axis.set_ylim(0, norm_ymax)
        label = normalized_axis.set_ylabel('IMF normalized TPA distribution',
                                           color='g')
        label.set_color('g')

    axis.legend(loc='upper left')

    if log:
        axis.set_xscale('log')

    axis.set_ylabel('Probability Distribution')
    axis.minorticks_on()

    return fg_hist_values, bg_hist_values, bins