def zoom_x_and_save(fig: matplotlib.figure.Figure, ax: matplotlib.axes.Axes,
                    figbase: str, plot_ext: str,
                    xzoom: List[Tuple[float, float]]) -> None:
    """
    Zoom in on subregions of the x-axis and save the figure.

    Arguments
    ---------
    fig : matplotlib.figure.Figure
        Figure to be processed.
    ax : matplotlib.axes.Axes
        Axes to be processed.
    fig_base : str
        Base name of the figure to be saved.
    plot_ext : str
        File extension of the figure to be saved.
    xzoom : List[list[float,float]]
        Values at which to split the x-axis.
    """
    xmin, xmax = ax.get_xlim()
    for ix in range(len(xzoom)):
        ax.set_xlim(xmin=xzoom[ix][0], xmax=xzoom[ix][1])
        figfile = (figbase + ".sub" + str(ix + 1) + plot_ext)
        savefig(fig, figfile)
    ax.set_xlim(xmin=xmin, xmax=xmax)
Beispiel #2
0
def _BetterCDF(data: List[float],
               ax: matplotlib.axes.Axes):
    # assumes that axes are already set to (min, max)
    data = np.sort(data)
    x_axis_min, x_axis_max = ax.get_xlim()
    n_points = len(data)
    has_quality_1_point = data[-1] == 1
    if has_quality_1_point:
        # don't print a drop off if the last data point(s)
        # have quality 1
        n_ones = sum(data == data[-1])
        data = np.hstack((
            [x_axis_min],
            data[0:(len(data) - n_ones)],
            [x_axis_max]
        ))
        ys = np.hstack((
            [1],
            np.arange(n_points - 1, n_ones - 1, -1) / np.float(n_points),
            [n_ones / np.float(n_points)]
        ))
    else:
        data = np.hstack((
            [x_axis_min],
            data,
            [x_axis_max]
        ))
        ys = np.hstack((
            [1],
            np.arange(n_points - 1, -1, -1) / np.float(n_points),
            [0]
        ))
    #ax.step(data, ys)#, where='post')
    ax.step(data, ys, where='post')
def plot_mesh(ax: matplotlib.axes.Axes,
              xe: numpy.ndarray,
              ye: numpy.ndarray,
              scale: float = 1000) -> None:
    """
    Add a mesh to a plot.
    
    Arguments
    ---------
    ax : matplotlib.axes.Axes
        Axes object in which to add the mesh.
    xe : numpy.ndarray
        M x 2 array of begin/end x-coordinates of mesh edges.
    ye : numpy.ndarray
        M x 2 array of begin/end y-coordinates of mesh edges.
    scale : float
        Indicates whether the axes are in m (1) or km (1000).
    """
    xe1 = xe[:, (0, 1, 1)] / scale
    xe1[:, 2] = numpy.nan
    xev = xe1.reshape((xe1.size, ))

    ye1 = ye[:, (0, 1, 1)] / scale
    ye1[:, 2] = numpy.nan
    yev = ye1.reshape((ye1.size, ))

    # to avoid OverflowError: In draw_path: Exceeded cell block limit
    # plot the data in chunks ...
    for i in range(0, len(xev), 3000):
        ax.plot(xev[i:i + 3000],
                yev[i:i + 3000],
                color=(0.5, 0.5, 0.5),
                linewidth=0.25)
Beispiel #4
0
def visualize_records(axs : matplotlib.axes.Axes, record : Record):
    previous = record.records[0]
    for current in record.records[1:]:
        xs = [previous[0], current[0]]
        ys = [previous[1], current[1]]
        previous = current
        axs.plot(xs, ys, color='black', linewidth=2.0)
def quantile_plot(
        ax: matplotlib.axes.Axes, x: np.ndarray, median: np.ndarray,
        lower: np.ndarray, upper: np.ndarray, shaded_kwargs: Dict[str, Any],
        line_kwargs: Dict[str, Any]) -> List[matplotlib.lines.Line2D]:
    """Create mean +- sd plot."""
    ax.fill_between(x, lower, upper, **shaded_kwargs)
    return ax.plot(x, median, **line_kwargs)
Beispiel #6
0
def draw_bbox(
    ax: matplotlib.axes.Axes,
    bbox: List,
    color: Tuple[int],
    text: str = None,
    alpha: float = 0.2,
) -> None:
    """Draw a bounding box on the matplotlib axes object."""
    # TODO: fix the bordering in matplotlib so that the pixels
    #   line up appropriately bounding boxes are [x, y, w, h]
    log.debug(f"Drawing bbox {bbox} {color}")
    r = Rectangle(
        (bbox[0], bbox[1]),
        (bbox[2]),
        (bbox[3]),
        linewidth=3,
        facecolor=color,
        edgecolor=color,
        alpha=alpha,
    )
    # Add text above box
    if text is not None:
        ax.text(
            x=bbox[0],
            y=bbox[1],
            s=text,
            color=color,
            weight="bold",
            fontsize=6,
            ha="left",
            va="bottom",
        )
    ax.add_patch(r)
Beispiel #7
0
    def plot_modes(self, ax: matplotlib.axes.Axes, n: int = 0, iq: int = 0):
        '''Plotting the phonon modes and its derivatives

        :param ax:
        :param n: the order of derivatives to be plotted:
            :math:`n = 0` for :math:`\\omega_{qm}(V)`,
            :math:`n = 1` for :math:`\\gamma_{qm}(V)`,
            :math:`n = 2` for :math:`V\\frac{\partial\gamma_{qm}(V)}{\partial V}`
        :param iq: the index of :math:`q` point to be plotted
        '''

        if n == 0:
            w_arrays = self.calculator.freq_array[:, iq, :]
        elif n == 1:
            w_arrays = self.calculator.mode_gamma[0][:, iq, :]
        elif n == 2:
            w_arrays = self.calculator.mode_gamma[1][:, iq, :]

        for k in range(self.calculator.np):
            if iq == 0 and k < 3: continue
            w_array = w_arrays[:, k]
            ax.plot(self.v_array, w_array)

        if n != 0: return

        for k in range(self.calculator.np):
            if iq == 0 and k < 3: continue
            freqs = numpy.array([
                volume.q_points[iq].modes[k]
                for volume in self.qha_input.volumes
            ])
            ax.scatter(self.volumes, freqs, s=10)
Beispiel #8
0
def ellispes(pcm: pyxpcm.pcm, ax1: matplotlib.axes.Axes) -> None:
    """Plot ellipses.

    Args:
        pcm (pyxpcm.pcm): pcm object.
        ax1 (matplotlib.axes.Axes): axes.
    """
    # pylint: disable=protected-access
    for i in range(pcm._classifier.covariances_.shape[0]):
        # pylint: disable=protected-access
        weight = pcm._classifier.weights_[i]
        # pylint: disable=protected-access
        mean = pcm._classifier.means_[i]

        # pylint: disable=protected-access
        _, s, rotation = la.svd(pcm._classifier.covariances_[i])
        for frac_sigma, alpha in [
            [1 / 9, 0.5 * weight],
            [1 / 4, 0.7 * weight],
            [1, weight],
        ]:

            radii = np.sqrt(s / frac_sigma)
            angle = np.arctan2(rotation[1, 0], rotation[0, 0]) / np.pi * 180

            e1 = patches.Ellipse(
                mean,
                radii[0],
                radii[1],
                angle=angle,
                alpha=alpha,  # color=color_array[i]
            )
            ax1.add_patch(e1)
            gp.label_subplots([ax1], start_from=1)
Beispiel #9
0
def plot_crosshairs(axes: mpl.axes.Axes, x_popt, y_popt, color: str = 'gray'):
    """ plot the cross-hairs on the hitmap

    Plot the cross-hairs that are the results from the fit of the projections
    """
    axes.vlines([x_popt[0]], 0, 1, color=color)
    axes.hlines([y_popt[0]], 0, 1, color=color)
Beispiel #10
0
def plot_shots_per_focal_length(subplot: matplotlib.axes.Axes,
                                data: pd.DataFrame) -> None:
    """
    Barplot of the number of shots per focal length (FF equivalent), on the provided subplot.

    Args:
        subplot: the subplot matplotlib.axes.Axes on which to plot.
        data: the pandas DataFrame with your exif data.

    Returns:
        Nothing, plots in place.
    """
    logger.debug("Plotting shots per focal length")
    sns.countplot(
        x="Focal_Range",
        hue="Lens",
        data=data,
        ax=subplot,
        order=data.Focal_Range.value_counts().index,
    )
    subplot.set_title("Number of shots per Focal Length (FF equivalent)",
                      fontsize=25)
    subplot.tick_params(axis="both", which="major", labelsize=13)
    subplot.set_xlabel("Focal Length", fontsize=20)
    subplot.set_ylabel("Number of Shots", fontsize=20)
    subplot.legend(loc="upper center", fontsize=15, title_fontsize=21)
Beispiel #11
0
    def add_pressure_ticks(self,
                           ax: matplotlib.axes.Axes,
                           interval: float = 1.0,
                           label: str = None):

        v_static, f_static = zip(
            *[(v_data.volume, v_data.energy)
              for v_data in self.calculator.qha_input.volumes])
        static_p_of_v = lambda v: _to_gpa(
            get_static_p_of_v(v_static, f_static)(_from_ang3(v)))

        ndec = max(-int(numpy.log10(interval)), 0)

        __ax = plt.gca()

        _ax = ax.twiny()
        _ax.set_xlim(*ax.get_xlim())
        _ax.xaxis.set_major_locator(
            PofVLocator(static_p_of_v, p_interval=interval))
        _ax.xaxis.set_minor_locator(
            PofVLocator(static_p_of_v, p_interval=interval / 5))
        _ax.xaxis.set_major_formatter(PofVFormatter(static_p_of_v, ndec=ndec))

        if label:
            _ax.set_xlabel(label)

        plt.sca(__ax)
Beispiel #12
0
def _rescale_ticks_and_units(ax: matplotlib.axes.Axes,
                             data: List[Dict[str, Any]],
                             cax: matplotlib.colorbar.Colorbar = None):
    """
    Rescale ticks and units for the provided axes as described in
    :meth:`~_make_rescaled_ticks_and_units`
    """
    # for x axis
    x_ticks_formatter, new_x_label = _make_rescaled_ticks_and_units(data[0])
    if x_ticks_formatter is not None and new_x_label is not None:
        ax.xaxis.set_major_formatter(x_ticks_formatter)
        ax.set_xlabel(new_x_label)

    # for y axis
    y_ticks_formatter, new_y_label = _make_rescaled_ticks_and_units(data[1])
    if y_ticks_formatter is not None and new_y_label is not None:
        ax.yaxis.set_major_formatter(y_ticks_formatter)
        ax.set_ylabel(new_y_label)

    # for z aka colorbar axis
    if cax is not None and len(data) > 2:
        z_ticks_formatter, new_z_label = _make_rescaled_ticks_and_units(
            data[2])
        if z_ticks_formatter is not None and new_z_label is not None:
            cax.set_label(new_z_label)
            cax.formatter = z_ticks_formatter
            cax.update_ticks()
Beispiel #13
0
def add_scalebar(
    ax: mpl.axes.Axes,
    scalebar_size: float,
    pixel_size: float,
    unit: str = "µm",
    edgecolor: str = None,
    **kwargs,
) -> None:
    """Add a scalebar to the axis."""
    # NOTE: this is to be moved to dphtools when the package is ready
    scalebar_length = scalebar_size / pixel_size
    default_scale_bar_kwargs = dict(
        loc="lower right",
        pad=0.5,
        color="white",
        frameon=False,
        size_vertical=scalebar_length / 10,
        fontproperties=fm.FontProperties(weight="bold"),
    )
    default_scale_bar_kwargs.update(kwargs)
    if unit is not None:
        label = f"{scalebar_size} {unit}"
    else:
        label = ""
        if "lower" in default_scale_bar_kwargs["loc"]:
            default_scale_bar_kwargs["label_top"] = True
    scalebar = AnchoredSizeBar(ax.transData, scalebar_length, label, **default_scale_bar_kwargs)
    if edgecolor:
        scalebar.size_bar.get_children()[0].set_edgecolor(edgecolor)
        scalebar.txt_label.get_children()[0].set_path_effects(
            [path_effects.Stroke(linewidth=2, foreground=edgecolor), path_effects.Normal()]
        )
    # add the scalebar
    ax.add_artist(scalebar)
Beispiel #14
0
def draw_poly(ax: mpl.axes.Axes, 
              left: float,
              bottom: float, 
              top: float, 
              right: float, 
              facecolor: str, 
              edgecolor: str, 
              zorder: int) -> None:
    '''Draw a set of polygrams given parrallel numpy arrays of left, bottom, top, right points'''
    XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T

    barpath = path.Path.make_compound_path_from_polys(XY)
    
    # Clean path to get rid of 0, 0 points.  Seems to be a matplotlib bug.  If we don't ylim lower bound is set to 0
    v = []
    c = []
    for seg in barpath.iter_segments():
        vertices, command = seg
        if not (vertices[0] == 0. and vertices[1] == 0.):
            v.append(vertices)
            c.append(command)
    cleaned_path = path.Path(v, c)

    patch = mptch.PathPatch(cleaned_path, facecolor=facecolor, edgecolor=edgecolor, zorder=zorder)
    ax.add_patch(patch)
Beispiel #15
0
def draw_boxplot(ax: mpl.axes.Axes,
                 names: str,
                 values: Sequence[np.ndarray],
                 proportional_widths: bool = True,
                 notched: bool = False,
                 show_outliers: bool = True,
                 show_means: bool = True,
                 show_all: bool = True) -> None:
    '''Draw a boxplot.  See BucketedValues class for explanation of arguments'''
    outliers = None if show_outliers else ''
    meanpointprops = dict(marker='D')
    assert (isinstance(values, list) and isinstance(names, list)
            and len(values) == len(names))
    widths = None

    if show_all:
        all_values = np.concatenate(values)
        values.append(all_values)
        names.append('all')

    if proportional_widths:
        counts = [len(v) for v in values]
        total = float(sum(counts))
        widths = [c / total for c in counts]

    ax.boxplot(values,
               notch=notched,
               sym=outliers,
               showmeans=show_means,
               meanprops=meanpointprops,
               widths=widths)
    ax.set_xticklabels(names)
Beispiel #16
0
def _rescale_ticks_and_units(
    ax: matplotlib.axes.Axes,
    data: Sequence[DSPlotData],
    cax: matplotlib.colorbar.Colorbar = None,
) -> None:
    """
    Rescale ticks and units for the provided axes as described in
    :func:`~_make_rescaled_ticks_and_units`
    """
    # for x axis
    if not _is_string_valued_array(data[0]['data']):
        x_ticks_formatter, new_x_label = \
            _make_rescaled_ticks_and_units(data[0])
        ax.xaxis.set_major_formatter(x_ticks_formatter)
        ax.set_xlabel(new_x_label)

    # for y axis
    if not _is_string_valued_array(data[1]['data']):
        y_ticks_formatter, new_y_label = \
            _make_rescaled_ticks_and_units(data[1])
        ax.yaxis.set_major_formatter(y_ticks_formatter)
        ax.set_ylabel(new_y_label)

    # for z aka colorbar axis
    if cax is not None and len(data) > 2:
        if not _is_string_valued_array(data[2]['data']):
            z_ticks_formatter, new_z_label = \
                _make_rescaled_ticks_and_units(data[2])
            cax.set_label(new_z_label)
            cax.formatter = z_ticks_formatter
            cax.update_ticks()
Beispiel #17
0
def plot_actogram(series: pd.Series,
                  dark=(19, 7),
                  ax: matplotlib.axes.Axes = None,
                  **kwargs):
    """Plot activity or displacement as an actogram.

    .. note::

       For published example see Eckel-Mahan K, Sassone-Corsi P. Phenotyping Circadian Rhythms in Mice.
       Curr Protoc Mouse Biol. 2015;5(3):271-281. Published 2015 Sep 1. doi:10.1002/9780470942390.mo140229

    """
    assert isinstance(series, pd.Series)
    assert is_datetime_or_timedelta_dtype(
        series.index
    ), f"Series must have datetime index but has {type(series.index)}"

    after_plot_args, _ = _get_after_plot_args(**kwargs)

    ax = series.plot(ax=ax)
    ax.set_ylabel(series.name)

    color_dark(series, ax, start=dark[0], end=dark[1])

    _process_after_plot_args(**after_plot_args)
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 #19
0
def _autoscale(ax: matplotlib.axes.Axes,
               axis: str = "y",
               sides: str = "both",
               margin: float = 0.1) -> None:
    """Autoscales the x or y axis of a given matplotlib ax object
    to fit the margins set by manually limits of the other axis,
    with margins in fraction of the width of the plot
    if sides is 'max' or 'min' then only adjust the limit on that side of axis"""
    assert axis in ["x", "y"]
    assert sides in ["both", "min", "max"]
    low, high = np.inf, -np.inf
    for artist in ax.collections + ax.lines:
        if axis == "y":
            set_lim = ax.set_ylim
            get_lim = ax.get_ylim
            cur_fixed_limit = ax.get_xlim()
            fixed, dependent = _get_xy(artist)
        else:
            set_lim = ax.set_xlim
            get_lim = ax.get_xlim
            cur_fixed_limit = ax.get_ylim()
            dependent, fixed = _get_xy(artist)
        low, high = _update_limts(low, high, fixed, dependent, cur_fixed_limit)
    margin = margin * (high - low)
    if low == np.inf and high == -np.inf:
        return
    assert low != np.inf and high != -np.inf
    new_min = (low - margin) if sides in ["both", "min"] else get_lim()[0]
    new_max = (high + margin) if sides in ["both", "max"] else get_lim()[1]
    set_lim(new_min, new_max)
Beispiel #20
0
def color_dark(series: pd.Series,
               ax: matplotlib.axes.Axes = None,
               start: int = 19,
               end: int = 7):
    """Color dark phase in plot."""
    assert is_datetime_or_timedelta_dtype(
        series.index
    ), f"Series must have datetime index but has {type(series.index)}"

    if not ax:
        ax = plt.gca()

    # get boundaries for dark times
    dark_mask = (series.index.hour >= start) | (series.index.hour < end)
    run_values, run_starts, run_lengths = find_runs(dark_mask)

    # highlighting
    for idx, is_dark in enumerate(run_values):
        if is_dark:
            start = run_starts[idx]
            end = run_starts[idx] + run_lengths[idx] - 1
            ax.axvspan(series.index[start],
                       series.index[end],
                       alpha=0.5,
                       color="gray")

    return ax
def company_distribution(df: pd.DataFrame, ax: mp.axes.Axes) -> ResultValue:
    log = logging.getLogger('company_distribution')
    log.info(" >>")
    try:

        def autopct_format(values):
            def my_format(pct):
                total = sum(values)
                val = int(round(pct * total / 100.0))
                str_val = f'{val:n}'
                return '{v:d}'.format(v=val)

            return my_format

        colors = [
            "#9aff33", "#34ff33", "#33ff98", "#33fffe", "#339aff", "#3371ff",
            "#5b33ff", "#c133ff", "#ff33d7"
        ]
        by_company = df.groupby(["fornitore"]).sum()
        by_company.reset_index(level=0, inplace=True)
        values = by_company["numero_dosi"]
        labels = by_company["fornitore"]
        ax.pie(values,
               labels=labels,
               colors=colors,
               autopct=autopct_format(values))
        ax.set_title("Vaccini consegnati", fontsize=18)

    except Exception as ex:
        log.error("Exception caught - {ex}".format(ex=ex))
        return ResultKo(ex)
    log.info(" <<")
    return ResultOk(True)
Beispiel #22
0
 def apply(self, ax: matplotlib.axes.Axes) -> None:
     if self.label:
         getattr(ax, f"set_{self.axis}label")(self.label, fontsize=self.font_size)
         # Set the tick font size too
         tick_font_size = self.tick_font_size if self.tick_font_size else self.font_size
         ax.tick_params(axis=self.axis, which="major", labelsize=tick_font_size)
     if self.log:
         getattr(ax, f"set_{self.axis}scale")("log")
         # Probably need to increase the number of ticks for a log axis. We just assume that's the case.
         # I really wish it handled this better by default...
         # See: https://stackoverflow.com/a/44079725/12907985
         major_locator = matplotlib.ticker.LogLocator(base=10, numticks=12)
         getattr(ax, f"{self.axis}axis").set_major_locator(major_locator)
         minor_locator = matplotlib.ticker.LogLocator(base=10.0, subs=np.linspace(0.2, 0.9, 8), numticks=12)
         getattr(ax, f"{self.axis}axis").set_minor_locator(minor_locator)
         # But we don't want to label these ticks.
         getattr(ax, f"{self.axis}axis").set_minor_formatter(matplotlib.ticker.NullFormatter())
     if self.range:
         min_range, max_range = self.range
         min_current_range, max_current_range = getattr(ax, f"get_{self.axis}lim")()
         if min_range is None:
             min_range = min_current_range
         if max_range is None:
             max_range = max_current_range
         getattr(ax, f"set_{self.axis}lim")([min_range, max_range])
Beispiel #23
0
def plot_shots_per_camera(subplot: matplotlib.axes.Axes,
                          data: pd.DataFrame) -> None:
    """
	Barplot of the number of shots per camera, on the provided subplot. Acts in place.

    Args:
        subplot: the subplot matplotlib.axes.Axes on which to plot.
        data: the pandas DataFrame with your exif data.

    Returns:
        Nothing, plots in place.

    ??? warning "There is a danger here"
        Here is an explanation of the danger.
        Here is how to bypass it :)
    """
    logger.debug("Plotting shots per camera")
    sns.countplot(y="Camera",
                  hue="Brand",
                  data=data,
                  ax=subplot,
                  order=data.Camera.value_counts().index)
    subplot.set_title("Number of Shots per Camera Model", fontsize=25)
    subplot.tick_params(axis="both", which="major", labelsize=13)
    subplot.set_xlabel("Number of Shots", fontsize=20)
    subplot.set_ylabel("Camera Model", fontsize=20)
    subplot.legend(loc="lower right", fontsize=18, title_fontsize=22)
Beispiel #24
0
    def apply(
        self,
        ax: matplotlib.axes.Axes,
        legend_handles: Optional[Sequence[matplotlib.container.ErrorbarContainer]] = None,
        legend_labels: Optional[Sequence[str]] = None,
    ) -> None:
        if self.location:
            kwargs = {}
            if legend_handles:
                kwargs["handles"] = legend_handles
            if legend_labels:
                kwargs["labels"] = legend_labels

            ax.legend(
                loc=self.location,
                bbox_to_anchor=self.anchor,
                # If we specify an anchor, we want to reduce an additional padding
                # to ensure that we have accurate placement.
                borderaxespad=(0 if self.anchor else None),
                borderpad=(0 if self.anchor else None),
                frameon=False,
                fontsize=self.font_size,
                ncol=self.ncol,
                handletextpad=self.marker_label_spacing,
                labelspacing=self.label_spacing,
                **kwargs,
            )
Beispiel #25
0
def color_dark(
    series: pd.Series, ax: matplotlib.axes.Axes = None, start: int = 19, end: int = 7
):
    """Color dark phase in plot.
    Args:

        series (pd.Series) - Time-series variable
        ax (:class: `~matplotlib.axes.Axes`): axis to plot on (eg, `plt.gca()`)
        start (int): start of dark period/night
        end (hour): end of dark period/day
    Returns:

        ax (:class:`~matplotlib.axes._subplots.AxesSubplot`): Axes of plot
    """
    assert is_datetime_or_timedelta_dtype(
        series.index
    ), f"Series must have datetime index but has {type(series.index)}"

    pd.plotting.register_matplotlib_converters()  # prevents type error with axvspan

    if not ax:
        ax = plt.gca()

    # get boundaries for dark times
    dark_mask = (series.index.hour >= start) | (series.index.hour < end)
    run_values, run_starts, run_lengths = find_runs(dark_mask)
    for idx, is_dark in enumerate(run_values):
        if is_dark:
            start = run_starts[idx]
            end = run_starts[idx] + run_lengths[idx] - 1
            ax.axvspan(series.index[start], series.index[end], alpha=0.5, color="gray")

    fig = plt.gcf()
    fig.autofmt_xdate()
    return ax
Beispiel #26
0
def plot_2pcf(ax: matplotlib.axes.Axes,
              dr: np.ndarray,
              xi0: np.ndarray,
              xi1: np.ndarray) -> None:
    """
    Plot the two-point correlation function for the x- and y-components of
    the astrometric residual field as a function of distance between
    points.

    Parameters
    ----------
    ax:
        Matplotlib axis in which to plot
    dr:
        separations at which the 2-point correlation functions were
        calculated
    xi0:
        2-point correlation function of the x-component of the astrometric
        residual field
    xi1:
        2-point correlation function of the y-component of the astrometric
        residual field

    Returns
    -------
    None
    """
    # Plot the two-point correlation functions as a function of distance
    ax.axhline(y=0, ls='--', lw=1, c='gray')
    ax.plot(dr, xi0, marker='o', ms=5, ls='-', lw=1, label=r'$\xi_{xx}$')
    ax.plot(dr, xi1, marker='o', ms=5, ls='-', lw=1, label=r'$\xi_{yy}$')
    ax.legend()
    ax.set_xlabel(r'$\Delta$ [degrees]', fontsize=12)
    ax.set_ylabel(r'$\xi(\Delta)$ [degrees$^2$]', fontsize=12)
Beispiel #27
0
def plot_on_a_plain_grid(x: np.ndarray, y: np.ndarray, z: np.ndarray,
                         ax: matplotlib.axes.Axes) -> matplotlib.axes.Axes:
    """
    Plot a heatmap of z using x and y as axes. Assumes that the data
    are rectangular, i.e. that x and y together describe a rectangular
    grid. The arrays of x and y need not be sorted in any particular
    way, but data must belong together such that z[n] has x[n] and
    y[n] as setpoints.  The setpoints need not be equidistantly
    spaced, but linear interpolation is used to find the edges of the
    plotted squares.

    Args:
        x: The x values
        y: The y values
        z: The z values

    Returns:
        The matplotlib figure handle
    """

    xrow, yrow, z_to_plot = reshape_2D_data(x, y, z)

    # we use a general edge calculator,
    # in the case of non-equidistantly spaced data
    # TODO: is this appropriate for a log ax?
    dxs = np.diff(xrow) / 2
    dys = np.diff(yrow) / 2
    x_edges = np.concatenate((np.array([xrow[0] - dxs[0]]), xrow[:-1] + dxs,
                              np.array([xrow[-1] + dxs[-1]])))
    y_edges = np.concatenate((np.array([yrow[0] - dys[0]]), yrow[:-1] + dys,
                              np.array([yrow[-1] + dys[-1]])))

    ax.pcolormesh(x_edges, y_edges, np.ma.masked_invalid(z_to_plot))

    return ax
def age_distribution(df: pd.DataFrame,
                     ax: mp.axes.Axes,
                     gender: str = "F") -> ResultValue:
    log = logging.getLogger('age_distribution')
    log.info(" >>")
    try:
        if gender.upper() not in ["M", "F", "B"]:
            msg = "Geneder {v} value not known".format(v=gender)
            log.error(msg)
            return ResultKo(Exception(msg))

        by_age = df.groupby(["fascia_anagrafica"]).sum()
        by_age.reset_index(level=0, inplace=True)
        by_age["totals"] = by_age["sesso_femminile"] + by_age["sesso_maschile"]

        values = by_age["sesso_femminile" if gender == "F" else
                        ("sesso_maschile" if gender == "M" else "totals")]
        labels = by_age["fascia_anagrafica"]
        ax.pie(values, labels=labels, autopct='%1.1f%%', colors=colors)
        ax.set_title("Distribuzione per eta'", fontsize=18)

    except Exception as ex:
        log.error("Exception caught - {ex}".format(ex=ex))
        return ResultKo(ex)
    log.info(" <<")
    return ResultOk(True)
def plot3_stacked_per_bank(
    ax: matplotlib.axes.Axes,
    km_mid: numpy.ndarray,
    km_step: float,
    dv: List[List[numpy.ndarray]],
    banklabel: str,
    wfrac: float,
) -> None:
    """
    Add a stacked plot of bank erosion with total eroded volume subdivided per bank to the selected axes.
    
    Arguments
    ---------
    fig : matplotlib.figure.Figure
        Figure object.
    ax : matplotlib.axes.Axes
        Axes object.
    km_mid : numpy.ndarray
        Array containing the mid points for the chainage bins.
    km_step : float
        Bin width.
    dv : List[List[numpy.ndarray]]
        List of nQ lists of N arrays containing the total erosion distance values
    banklabel : str
        Label for bank id.
    wfrac : float
        Width fraction for the stacked column.
    
    Results
    -------
    None
    """
    n_banklines = len(dv[0])
    clrs = get_colors("plasma", n_banklines + 1)
    for ib in range(n_banklines):
        for iq in range(len(dv)):
            if iq == 0:
                dvq = dv[iq][ib].copy()
            else:
                dvq = dvq + dv[iq][ib]
        if ib == 0:
            ax.bar(
                km_mid,
                dvq,
                width=wfrac * km_step,
                color=clrs[ib],
                label=banklabel.format(ib=ib + 1),
            )
            cumdv = dvq
        else:
            ax.bar(
                km_mid,
                dvq,
                width=wfrac * km_step,
                bottom=cumdv,
                color=clrs[ib],
                label=banklabel.format(ib=ib + 1),
            )
            cumdv = cumdv + dvq
Beispiel #30
0
    def format_ticks(self, ax: mpl.axes.Axes):
        """Remove labels and ticks from mpl.axes.

        Keyword arguments:
        ax -- matplotlib.axes.Axes on which to apply changes
        """
        ax.tick_params(axis='x', which='both', bottom=False, labelbottom=False)
        ax.tick_params(axis='y', which='both', left=False, labelleft=False)
Beispiel #31
0
    def __init__(
            self,
            ax: mpl.axes.Axes,
            layer: LayerData,
            cmaps: dict,
            vlims: dict,
            contours: dict,
            extent, interpolation, mask=None):
        self.ax = ax
        self._meas = layer.y.info.get('meas')
        self._contours = layer.contour_plot_args(contours)
        self._data = self._data_from_ndvar(layer.y)
        self._extent = extent
        self._mask = mask

        if layer.plot_type == PlotType.IMAGE:
            kwargs = layer.im_plot_args(vlims, cmaps)
            self.im = ax.imshow(self._data, origin='lower', aspect=self._aspect, extent=extent, interpolation=interpolation, **kwargs)
            if mask is not None:
                self.im.set_clip_path(mask)
            self._cmap = kwargs['cmap']
            self.vmin, self.vmax = self.im.get_clim()
        elif layer.plot_type == PlotType.CONTOUR:
            self.im = None
            self.vmin = self.vmax = None
        else:
            raise RuntimeError(f"layer of type {layer.plot_type}")

        # draw flexible parts
        self._contour_h = None
        self._draw_contours()
 def plot_misses_against_hits(ax: mpl.axes.Axes, x: Sequence[int], y: Sequence[int], **kwargs) -> mpl.collections.PathCollection:
     ax.set_xlabel("Cache misses")
     ax.set_ylabel("Cache hits")
     return ax.scatter(x, y, edgecolors="none", **kwargs)