예제 #1
0
 def draw_path(self, path, properties: Properties, z: float):
     pattern = self.pattern(properties)
     lineweight = self.lineweight(properties)
     color = properties.color
     if len(pattern) < 2:
         vertices, codes = _get_path_patch_data(path)
         patch = PathPatch(
             Path(vertices, codes),
             linewidth=lineweight,
             color=color,
             fill=False,
             zorder=z,
         )
         self.ax.add_patch(patch)
     else:
         renderer = EzdxfLineTypeRenderer(pattern)
         segments = renderer.line_segments(
             path.flattening(self._config.max_flattening_distance,
                             segments=16))
         lines = LineCollection(
             [((s.x, s.y), (e.x, e.y)) for s, e in segments],
             linewidths=lineweight,
             color=color,
             zorder=z,
         )
         lines.set_capstyle("butt")
         self.ax.add_collection(lines)
예제 #2
0
class BatchLineCollection(object):
    def __init__(self, ax):
        self._ax = ax
        self._lc = None

    @property
    def artists(self):
        return [self._lc]

    def draw(self, x, y, **kwargs):
        segments = []
        for x_i, y_i in zip(x, y):
            xy_i = np.stack([x_i, y_i], axis=1)
            xy_i = xy_i.reshape(-1, 1, 2)
            segments_i = np.hstack([xy_i[:-1], xy_i[1:]])
            segments.append(segments_i)
        segments = np.concatenate(segments, axis=0)

        if self._lc is None:
            self._lc = PltLineCollection(segments)
            self._ax.add_collection(self._lc)
        else:
            self._lc.set_segments(segments)
        if 'color' in kwargs:
            self._lc.set_color(np.reshape(kwargs['color'],
                                          [len(segments), -1]))
        if 'linewidth' in kwargs:
            self._lc.set_linewidth(kwargs['linewidth'])
        self._lc.set_joinstyle('round')
        self._lc.set_capstyle('round')
예제 #3
0
 def draw_line(self, start: Vec3, end: Vec3, properties: Properties,
               z: float):
     pattern = self.pattern(properties)
     lineweight = self.lineweight(properties)
     color = properties.color
     if len(pattern) < 2:
         self.ax.add_line(
             Line2D(
                 (start.x, end.x),
                 (start.y, end.y),
                 linewidth=lineweight,
                 color=color,
                 zorder=z,
             ))
     else:
         renderer = EzdxfLineTypeRenderer(pattern)
         lines = LineCollection(
             [((s.x, s.y), (e.x, e.y))
              for s, e in renderer.line_segment(start, end)],
             linewidths=lineweight,
             color=color,
             zorder=z,
         )
         lines.set_capstyle("butt")
         self.ax.add_collection(lines)
예제 #4
0
def test_cap_and_joinstyle_image():
    fig, ax = plt.subplots()
    ax.set_xlim([-0.5, 1.5])
    ax.set_ylim([-0.5, 2.5])

    x = np.array([0.0, 1.0, 0.5])
    ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]])

    segs = np.zeros((3, 3, 2))
    segs[:, :, 0] = x
    segs[:, :, 1] = ys
    line_segments = LineCollection(segs, linewidth=[10, 15, 20])
    line_segments.set_capstyle("round")
    line_segments.set_joinstyle("miter")

    ax.add_collection(line_segments)
    ax.set_title('Line collection with customized caps and joinstyle')
예제 #5
0
def test_cap_and_joinstyle_image():
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.set_xlim([-0.5, 1.5])
    ax.set_ylim([-0.5, 2.5])

    x = np.array([0.0, 1.0, 0.5])
    ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]])

    segs = np.zeros((3, 3, 2))
    segs[:, :, 0] = x
    segs[:, :, 1] = ys
    line_segments = LineCollection(segs, linewidth=[10, 15, 20])
    line_segments.set_capstyle("round")
    line_segments.set_joinstyle("miter")

    ax.add_collection(line_segments)
    ax.set_title('Line collection with customized caps and joinstyle')
예제 #6
0
def colorline(
    x,
    y,
    z=None,
    cmap="inferno",
    norm=plt.Normalize(0.0, 1.0),
    linewidth=3,
    alpha=1.0,
    ax=None,
    autoscale=True,
):
    """Plot a colored line with coordinates x and y.

    Optionally specify colors in the array z
    Optionally specify a colormap, a norm function and a line width
    """
    if not isinstance(cmap, Colormap):
        cmap = plt.get_cmap(cmap)

    # Default colors equally spaced on [0,1]:
    if z is None:
        z = np.linspace(0.0, 1.0, len(x))

    # Special case if a single number:
    if not hasattr(z, "__iter__"):  # to check for numerical input -- this is a hack
        z = np.array([z])

    z = np.asarray(z)

    segments = make_segments(x, y)
    lc = LineCollection(segments, array=z, cmap=cmap, norm=norm, linewidth=linewidth, alpha=alpha)

    lc.set_capstyle("round")

    if ax is None:
        ax = plt.gca()
    ax.add_collection(lc)

    if autoscale:
        ax.autoscale()

    return lc
예제 #7
0
    def plot(self, img, trajectories, frame_id, trail_len):
        """Plot projections of trajectories over image."""
        # TODO: Make this more object oriented (no arguments) or completely functional (pass fig and ax as arguments).

        img = cv2.cvtColor(
            img,
            cv2.COLOR_BGR2RGB)  # Change color space for matplotlib plotting

        # Prepare for plotting
        self.ax.clear()
        self.ax.axis('off')
        self.ax.imshow(img, interpolation='nearest')  # This takes too long...

        # Handle case where not enough points for full trail length
        if frame_id > trail_len:
            plot_range = np.arange(frame_id - trail_len, frame_id)
        else:
            plot_range = np.arange(0, frame_id)

        line_widths = np.linspace(0.5, 3,
                                  trail_len)  # Same line width for all drones

        for i, traj in enumerate(trajectories):
            color = self.cmap(i / 20)
            line_colors = np.linspace(
                (*color[:3], 0), color, trail_len,
                axis=0)  # Fade trail color to transparent
            traj = traj[plot_range, np.newaxis, :]
            segments = np.concatenate([traj[:-1], traj[1:]], axis=1)
            lines = LineCollection(segments,
                                   linewidths=line_widths,
                                   colors=line_colors)
            lines.set_capstyle('round')
            self.ax.add_collection(lines)

        # Retrieve view of render buffer. See: https://stackoverflow.com/a/62040123
        self.fig.canvas.draw()
        buf = self.fig.canvas.buffer_rgba()
        out_frame = cv2.cvtColor(np.asarray(buf), cv2.COLOR_RGB2BGR)

        return out_frame
예제 #8
0
파일: plotting.py 프로젝트: Pabce/tardis
    def get_solid_line(y, c_map, width, color, onecolor=None, limits=None):
        points = np.array([y[3, :], y[2, :]]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)

        if onecolor:
            color = np.array([onecolor] * len(y[0, :]))
            lc = LineCollection(segments, colors=color)
        else:
            if limits:
                norm = plt.Normalize(limits[0], limits[1])
                lc = LineCollection(segments, cmap=c_map, norm=norm)
            else:
                lc = LineCollection(segments, cmap=c_map)

            lc.set_array(color)

        lc.set_linewidth(width)

        #lc.set_joinstyle('bevel')
        lc.set_snap(False)
        lc.set_capstyle('round') #projecting
        lc.set_antialiased(True)

        return lc
예제 #9
0
    def plot(self, ax, kws):
        """Draw the plot onto an axes, passing matplotlib kwargs."""

        # Draw a test line, using the passed in kwargs. The goal here is to
        # honor both (a) the current state of the plot cycler and (b) the
        # specified kwargs on all the lines we will draw, overriding when
        # relevant with the lineplot semantics. Note that we won't cycle
        # internally; in other words, if ``hue`` is not used, all lines
        # will have the same color, but they will have the color that
        # ax.plot() would have used for a single line, and calling lineplot
        # will advance the axes property cycle.

        scout, = ax.plot([], [], **kws)

        orig_color = kws.pop("color", scout.get_color())
        orig_marker = kws.pop("marker", scout.get_marker())
        orig_linewidth = kws.pop("linewidth",
                                 kws.pop("lw", scout.get_linewidth()))

        orig_dashes = kws.pop("dashes", "")

        kws.setdefault("markeredgewidth", kws.pop("mew", .75))
        kws.setdefault("markeredgecolor", kws.pop("mec", "w"))

        scout.remove()

        # Loop over the semantic subsets and draw a line for each

        for semantics, data in self.subset_data():

            hue, size, style = semantics
            x, y, units = data["x"], data["y"], data.get("units", None)

            if self.estimator is not None:
                if self.units is not None:
                    err = "estimator must be None when specifying units"
                    raise ValueError(err)
                x, y, y_ci = self.aggregate(y, x, units)
            else:
                y_ci = None

            kws["color"] = self.palette.get(hue, orig_color)
            kws["dashes"] = self.dashes.get(style, orig_dashes)
            kws["marker"] = self.markers.get(style, orig_marker)
            kws["linewidth"] = self.sizes.get(size, orig_linewidth)

            # --- Draw the main line

            line, = ax.plot([], [], **kws)
            line_color = line.get_color()
            line_alpha = line.get_alpha()
            line_capstyle = line.get_solid_capstyle()
            line.remove()

            if self.units is None:

                line, = ax.plot(x.values, y.values, **kws)

            else:

                for u in units.unique():
                    ax.plot(x[units == u].values, y[units == u].values, **kws)

            # --- Draw the confidence intervals

            if y_ci is not None:

                if self.errstyle == "band":

                    ax.fill_between(x,
                                    y_ci["low"],
                                    y_ci["high"],
                                    color=line_color,
                                    alpha=.2)

                elif self.errstyle == "bars":

                    ci_xy = np.empty((len(x), 2, 2))
                    ci_xy[:, :, 0] = x[:, np.newaxis]
                    ci_xy[:, :, 1] = y_ci.values
                    lines = LineCollection(ci_xy,
                                           color=line_color,
                                           alpha=line_alpha)
                    try:
                        lines.set_capstyle(line_capstyle)
                    except AttributeError:
                        pass
                    ax.add_collection(lines)
                    ax.autoscale_view()

                else:
                    err = "`errstyle` must by 'band' or 'bars', not {}"
                    raise ValueError(err.format(self.errstyle))

        # TODO this should go in its own method?
        if self.x_label is not None:
            x_visible = any(t.get_visible() for t in ax.get_xticklabels())
            ax.set_xlabel(self.x_label, visible=x_visible)
        if self.y_label is not None:
            y_visible = any(t.get_visible() for t in ax.get_yticklabels())
            ax.set_ylabel(self.y_label, visible=y_visible)

        # Add legend
        if self.legend:
            self.add_legend_data(ax)
            handles, _ = ax.get_legend_handles_labels()
            if handles:
                ax.legend()
예제 #10
0
                       figsize=(4.5, 5),
                       subplot_kw={'projection': 'polar'})

#ax.plot(data['phase'][idx_plt], data['radius'][idx_plt])
num_pts = idx_plt.shape[0]
res = 10
time = data['time'][idx_plt][0::res]
phase = data['phase'][idx_plt][0::res]
radius = data['radius'][idx_plt][0::res]

cnorm = mpl.colors.Normalize(vmin=0, vmax=8)
points = np.array([phase, radius]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, cmap=cm.plasma, norm=cnorm)
lc.set_array(time)
lc.set_capstyle('round')
ax.add_collection(lc)
ax.set_rgrids(np.arange(0.4, 1.6, 0.4))
ax.set_rmax(1.2)
ax.set_xlabel('Hip Angle Axis', labelpad=10)
ax.set_ylabel('Hip Integral Axis', labelpad=35)

# add an axes above the main axes.
cax = fig.add_axes([0.11, 1.0, 0.8, 0.05])
cb = mpl.colorbar.ColorbarBase(cax,
                               cmap=cm.plasma,
                               norm=cnorm,
                               orientation='horizontal',
                               drawedges=False)
# change tick position to top. Tick position defaults to bottom and overlaps
# the image.