Exemplo n.º 1
0
def update_plot(
    y: Metric,
    fig: plt.Figure,
    ax: plt.Axes,
    line: list[plt.Line2D],
    display_id: DisplayHandle,
    window: int = 15,
    logging_steps: int = 1,
):
    if not in_notebook():
        return

    y = np.array(y)
    if len(y.shape) == 2:
        y = y.mean(-1)

    yavg = moving_average(y.squeeze(), window=window)
    line[0].set_ydata(yavg)
    line[0].set_xdata(logging_steps * np.arange(yavg.shape[0]))
    #  line[0].set_ydata(y)
    #  line[0].set_xdata(plot_freq * np.arange(y.shape[0]))
    #  line[0].set_xdata(np.arange(len(yavg)))
    ax.relim()
    ax.autoscale_view()
    fig.canvas.draw()
    display_id.update(fig)
Exemplo n.º 2
0
def traj_colormap(ax: plt.Axes,
                  traj: trajectory.PosePath3D,
                  array: ListOrArray,
                  plot_mode: PlotMode,
                  min_map: float,
                  max_map: float,
                  title: str = "",
                  fig: typing.Optional[mpl.figure.Figure] = None) -> None:
    """
    color map a path/trajectory in xyz coordinates according to
    an array of values
    :param ax: plot axis
    :param traj: trajectory.PosePath3D or trajectory.PoseTrajectory3D object
    :param array: Nx1 array of values used for color mapping
    :param plot_mode: PlotMode
    :param min_map: lower bound value for color mapping
    :param max_map: upper bound value for color mapping
    :param title: plot title
    :param fig: plot figure. Obtained with plt.gcf() if none is specified
    """
    pos = traj.positions_xyz
    norm = mpl.colors.Normalize(vmin=min_map, vmax=max_map, clip=True)
    mapper = cm.ScalarMappable(
        norm=norm,
        cmap=SETTINGS.plot_trajectory_cmap)  # cm.*_r is reversed cmap
    mapper.set_array(array)
    colors = [mapper.to_rgba(a) for a in array]
    line_collection = colored_line_collection(pos, colors, plot_mode)
    ax.add_collection(line_collection)
    ax.autoscale_view(True, True, True)
    if plot_mode == PlotMode.xyz:
        ax.set_zlim(np.amin(traj.positions_xyz[:, 2]),
                    np.amax(traj.positions_xyz[:, 2]))
        if SETTINGS.plot_xyz_realistic:
            set_aspect_equal_3d(ax)
    if fig is None:
        fig = plt.gcf()
    cbar = fig.colorbar(
        mapper, ticks=[min_map, (max_map - (max_map - min_map) / 2), max_map])
    cbar.ax.set_yticklabels([
        "{0:0.3f}".format(min_map),
        "{0:0.3f}".format(max_map - (max_map - min_map) / 2),
        "{0:0.3f}".format(max_map)
    ])

    if title:
        ax.legend(frameon=True)
        ax.set_title(title)
Exemplo n.º 3
0
def drawRects(ax: plt.Axes,
              data,
              facecolor=None,
              alpha: float = None,
              edgecolor=None,
              linewidth: float = None,
              profile: dict = None,
              autolim=True) -> None:
    """
    Draw multiple rectangles

    Args:
        ax: the plot axes
        data: either a 2D array of shape (num. rectangles, 4), or a list of tuples
            (x0, y0, x1, y1), where each row is a rectangle
        color: the face color
        edgecolor: the color of the edges
        alpha: alpha value for the rectangle (both facecolor and edgecolor)
        label: if given, a label is plotted at the center of the rectangle
        profile: the profile used, or None for default
        autolim: autoscale view
    """
    facecolor = _fallbackColor(facecolor, profile, key='facecolor')
    edgecolor = _fallbackColor(edgecolor, profile, key='edgecolor')
    linewidth = _fallback(linewidth, profile, 'linewidth')
    rects = []
    for coords in data:
        x0, y0, x1, y1 = coords
        rect = Rectangle((x0, y0), x1 - x0, y1 - y0)
        rects.append(rect)
    coll = PatchCollection(rects,
                           linewidth=linewidth,
                           alpha=alpha,
                           edgecolor=edgecolor,
                           facecolor=facecolor)
    ax.add_collection(coll, autolim=True)
    if autolim:
        ax.autoscale_view()
Exemplo n.º 4
0
def autoscaleAxis(ax: plt.Axes) -> None:
    ax.relim()
    ax.autoscale_view(True, True, True)
Exemplo n.º 5
0
def cancellation_progression(cnclp: CnclProg, model_output: int = None,
                             *, color_cycle: Sequence = None,
                             ax: plt.Axes = None, figsize=(8.0, 6.0), title: str = None,
                             xlabel="Estimated cancellation", ylabel="True cancellation", legend=True):
    if model_output is None:
        test_array = next(iter(next(iter(cnclp.values())).values()))
        if test_array.ndim != 2:
            n_model_outputs = test_array.shape[2]
            if n_model_outputs != 1:
                raise ValueError("When plotting cancellation progressions, the model_output argument can only be "
                                 "omitted when there is only one model output in the progression. However, this "
                                 f"progression stores {n_model_outputs} model outputs. So, please supply model_output.")
            else:
                model_output = 0

    # Create figure if necessary.
    if ax is None:
        ax = plt.figure(figsize=figsize).gca()

    # Set title, xlabel, and ylabel if applicable.
    if title is not None:
        ax.set_title(title)
    if xlabel is not None:
        ax.set_xlabel(xlabel)
    if ylabel is not None:
        ax.set_ylabel(ylabel)

    if color_cycle is None:
        color_cycle = _DEFAULT_COLOR_CYCLE

    for (om, om_cnclp), base_color in zip(cnclp.items(), cycle(color_cycle)):
        color_hue = rgb_to_hsv(to_rgb(base_color))[0]

        for (frag, frag_cnclp), color_value in zip(om_cnclp.items(), np.linspace(1, 0.7, len(om_cnclp))):
            if model_output is not None:
                frag_cnclp = frag_cnclp[model_output]

            if not np.all(np.isnan(frag_cnclp[:, 1])):
                third_col_max = int(frag_cnclp[0, 2])

                max_sat_color = hsv_to_rgb([color_hue, 1.0, color_value])
                min_sat_color = hsv_to_rgb([color_hue, 0.2, color_value])
                # Use linspace in the wrong order and then reverse the result, such that when
                # 'third_col_max' is 1, the cmap contains the max saturation and not the
                # min saturation color as its only color.
                cmap = ListedColormap(np.linspace(max_sat_color, min_sat_color, third_col_max)[::-1])

                segments = list(zip(frag_cnclp[:-1, :2], frag_cnclp[1:, :2]))
                lc = LineCollection(segments, cmap=cmap, norm=plt.Normalize(1, third_col_max),
                                    label=f"{type(om).__name__[0]}~{frag}", color=max_sat_color, zorder=1)
                lc.set_array(frag_cnclp[1:, 2])
                ax.add_collection(lc)

    # Necessary because 'ax.add_collection()' doesn't adjust xlim and ylim automatically.
    ax.autoscale_view()

    # Draw the diagonal dotted line.
    diag = [max(ax.get_xlim()[0], ax.get_ylim()[0]),
            min(ax.get_xlim()[1], ax.get_ylim()[1])]
    ax.plot(diag, diag, ls="dotted", color="gray", zorder=0)

    if legend:
        ax.legend(loc="upper left", bbox_to_anchor=(1.01, 0, 1, 1))