Python matplotlib.collections.LineCollection() Examples

The following are 30 code examples of matplotlib.collections.LineCollection(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.collections , or try the search function .
Example #1
Source File: evaluation.py    From tsinfer with GNU General Public License v3.0 7 votes vote down vote up
def edge_plot(ts, filename):
    n = ts.num_samples
    pallete = sns.color_palette("husl", 2 ** n - 1)
    lines = []
    colours = []
    for tree in ts.trees():
        left, right = tree.interval
        for u in tree.nodes():
            children = tree.children(u)
            # Don't bother plotting unary nodes, which will all have the same
            # samples under them as their next non-unary descendant
            if len(children) > 1:
                for c in children:
                    lines.append([(left, c), (right, c)])
                    colours.append(pallete[unrank(tree.samples(c), n)])

    lc = mc.LineCollection(lines, linewidths=2, colors=colours)
    fig, ax = plt.subplots()
    ax.add_collection(lc)
    ax.autoscale()
    save_figure(filename) 
Example #2
Source File: colorbar.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def add_lines(self, levels, colors, linewidths):
        '''
        Draw lines on the colorbar. It deletes preexisting lines.
        '''
        del self.lines

        N = len(levels)
        x = np.array([1.0, 2.0])
        X, Y = np.meshgrid(x,levels)
        if self.orientation == 'vertical':
            xy = [zip(X[i], Y[i]) for i in range(N)]
        else:
            xy = [zip(Y[i], X[i]) for i in range(N)]
        col = collections.LineCollection(xy, linewidths=linewidths,
                                         )
        self.lines = col
        col.set_color(colors)
        self.ax.add_collection(col) 
Example #3
Source File: reference-scales.py    From matplotlib-cheatsheet with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def grid(ax):
    segments,colors,linewidths = [], [], []
    for x in ax.xaxis.get_minorticklocs():
        segments.append([(x,ymin), (x,ymax)])
        colors.append("0.75")
        linewidths.append(0.50)
    for x in ax.xaxis.get_majorticklocs():
        segments.append([(x,ymin), (x,ymax)])
        colors.append("0.50")
        linewidths.append(0.75)
    for y in ax.yaxis.get_minorticklocs():
        segments.append([(xmin,y), (xmax,y)])
        colors.append("0.75")
        linewidths.append(0.50)
    for y in ax.yaxis.get_majorticklocs():
        segments.append([(xmin,y), (xmax,y)])
        colors.append("0.50")
        linewidths.append(0.75)

    collection = LineCollection(segments, zorder=-10,
                                colors=colors, linewidths=linewidths)
    ax.add_collection(collection) 
Example #4
Source File: guide_colorbar.py    From plotnine with GNU General Public License v2.0 6 votes vote down vote up
def add_ticks(da, locations, direction):
    segments = [None] * (len(locations)*2)
    if direction == 'vertical':
        x1, x2, x3, x4 = np.array([0.0, 1/5, 4/5, 1.0]) * da.width
        for i, y in enumerate(locations):
            segments[i*2:i*2+2] = [((x1, y), (x2, y)),
                                   ((x3, y), (x4, y))]
    else:
        y1, y2, y3, y4 = np.array([0.0, 1/5, 4/5, 1.0]) * da.height
        for i, x in enumerate(locations):
            segments[i*2:i*2+2] = [((x, y1), (x, y2)),
                                   ((x, y3), (x, y4))]

    coll = mcoll.LineCollection(segments,
                                color='#CCCCCC',
                                linewidth=1,
                                antialiased=False)
    da.add_artist(coll) 
Example #5
Source File: graph.py    From coiltraine with MIT License 6 votes vote down vote up
def plot_ori(self, c):
        from matplotlib import collections as mc

        import matplotlib.pyplot as plt
        line_len = 1

        lines = [[(p[0], p[1]), (p[0] + line_len * self._angles[p][0],
                                 p[1] + line_len * self._angles[p][1])] for p in self._nodes]
        lc = mc.LineCollection(lines, linewidth=2, color='green')
        _, ax = plt.subplots()
        ax.add_collection(lc)

        ax.autoscale()
        ax.margins(0.1)

        xs = [p[0] for p in self._nodes]
        ys = [p[1] for p in self._nodes]

        plt.scatter(xs, ys, color=c) 
Example #6
Source File: plot.py    From evo with GNU General Public License v3.0 6 votes vote down vote up
def colored_line_collection(xyz, colors, plot_mode=PlotMode.xy,
                            linestyles="solid", step=1, alpha=1.):
    if len(xyz) / step != len(colors):
        raise PlotException(
            "color values don't have correct length: %d vs. %d" %
            (len(xyz) / step, len(colors)))
    x_idx, y_idx, z_idx = plot_mode_to_idx(plot_mode)
    xs = [[x_1, x_2]
          for x_1, x_2 in zip(xyz[:-1:step, x_idx], xyz[1::step, x_idx])]
    ys = [[x_1, x_2]
          for x_1, x_2 in zip(xyz[:-1:step, y_idx], xyz[1::step, y_idx])]
    if plot_mode == PlotMode.xyz:
        zs = [[x_1, x_2]
              for x_1, x_2 in zip(xyz[:-1:step, z_idx], xyz[1::step, z_idx])]
        segs = [list(zip(x, y, z)) for x, y, z in zip(xs, ys, zs)]
        line_collection = art3d.Line3DCollection(segs, colors=colors,
                                                 alpha=alpha,
                                                 linestyles=linestyles)
    else:
        segs = [list(zip(x, y)) for x, y in zip(xs, ys)]
        line_collection = LineCollection(segs, colors=colors, alpha=alpha,
                                         linestyle=linestyles)
    return line_collection 
Example #7
Source File: graphs.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def init_artists(self, ax, plot_args, plot_kwargs):
        artists = {}
        if 'arcs' in plot_args:
            color_opts = ['c', 'cmap', 'vmin', 'vmax', 'norm']
            groups = [g for g in self._style_groups if g != 'arc']
            edge_opts = filter_styles(plot_kwargs, 'arc', groups, color_opts)
            paths = plot_args['arcs']
            edges = LineCollection(paths, **edge_opts)
            ax.add_collection(edges)
            artists['arcs'] = edges

        artists.update(super(ChordPlot, self).init_artists(ax, plot_args, plot_kwargs))
        if 'text' in plot_args:
            fontsize = plot_kwargs.get('text_font_size', 8)
            labels = []
            for (x, y, l, a) in zip(*plot_args['text']):
                label = ax.annotate(l, xy=(x, y), xycoords='data', rotation=a,
                                    horizontalalignment='left', fontsize=fontsize,
                                    verticalalignment='center', rotation_mode='anchor')
                labels.append(label)
            artists['labels'] = labels
        return artists 
Example #8
Source File: colorbar.py    From Computable with MIT License 6 votes vote down vote up
def add_lines(self, levels, colors, linewidths):
        '''
        Draw lines on the colorbar. It deletes preexisting lines.
        '''
        del self.lines

        N = len(levels)
        x = np.array([1.0, 2.0])
        X, Y = np.meshgrid(x,levels)
        if self.orientation == 'vertical':
            xy = [zip(X[i], Y[i]) for i in range(N)]
        else:
            xy = [zip(Y[i], X[i]) for i in range(N)]
        col = collections.LineCollection(xy, linewidths=linewidths,
                                         )
        self.lines = col
        col.set_color(colors)
        self.ax.add_collection(col) 
Example #9
Source File: test_legend.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_linecollection_scaled_dashes():
    lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]
    lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]
    lines3 = [[[0.6, .2], [.8, .4]], [[.5, .7], [.1, .1]]]
    lc1 = mcollections.LineCollection(lines1, linestyles="--", lw=3)
    lc2 = mcollections.LineCollection(lines2, linestyles="-.")
    lc3 = mcollections.LineCollection(lines3, linestyles=":", lw=.5)

    fig, ax = plt.subplots()
    ax.add_collection(lc1)
    ax.add_collection(lc2)
    ax.add_collection(lc3)

    leg = ax.legend([lc1, lc2, lc3], ["line1", "line2", 'line 3'])
    h1, h2, h3 = leg.legendHandles

    for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)):
        assert oh.get_linestyles()[0][1] == lh._dashSeq
        assert oh.get_linestyles()[0][0] == lh._dashOffset 
Example #10
Source File: test_collections.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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') 
Example #11
Source File: vis.py    From wradlib with MIT License 6 votes vote down vote up
def add_lines(ax, lines, **kwargs):
    """Add lines (points in the form Nx2) to axes

    Add lines (points in the form Nx2) to existing axes ax
    using :class:`matplotlib:matplotlib.collections.LineCollection`.

    Parameters
    ----------
    ax : :class:`matplotlib:matplotlib.axes.Axes`
    lines : :class:`numpy:numpy.ndarray`
        nested Nx2 array(s)
    kwargs : :class:`matplotlib:matplotlib.collections.LineCollection`

    Examples
    --------
    See :ref:`/notebooks/visualisation/wradlib_overlay.ipynb`.
    """
    try:
        ax.add_collection(LineCollection([lines], **kwargs))
    except AssertionError:
        ax.add_collection(LineCollection([lines[None, ...]], **kwargs))
    except ValueError:
        for line in lines:
            add_lines(ax, line, **kwargs) 
Example #12
Source File: graph.py    From Hands-On-Intelligent-Agents-with-OpenAI-Gym with MIT License 6 votes vote down vote up
def plot_ori(self, c):
        from matplotlib import collections as mc

        import matplotlib.pyplot as plt
        line_len = 1

        lines = [[(p[0], p[1]), (p[0] + line_len * self._angles[p][0],
                                 p[1] + line_len * self._angles[p][1])] for p in self._nodes]
        lc = mc.LineCollection(lines, linewidth=2, color='green')
        _, ax = plt.subplots()
        ax.add_collection(lc)

        ax.autoscale()
        ax.margins(0.1)

        xs = [p[0] for p in self._nodes]
        ys = [p[1] for p in self._nodes]

        plt.scatter(xs, ys, color=c) 
Example #13
Source File: graph.py    From Hands-On-Intelligent-Agents-with-OpenAI-Gym with MIT License 6 votes vote down vote up
def plot_ori(self, c):
        from matplotlib import collections as mc

        import matplotlib.pyplot as plt
        line_len = 1

        lines = [[(p[0], p[1]), (p[0] + line_len * self._angles[p][0],
                                 p[1] + line_len * self._angles[p][1])] for p in self._nodes]
        lc = mc.LineCollection(lines, linewidth=2, color='green')
        _, ax = plt.subplots()
        ax.add_collection(lc)

        ax.autoscale()
        ax.margins(0.1)

        xs = [p[0] for p in self._nodes]
        ys = [p[1] for p in self._nodes]

        plt.scatter(xs, ys, color=c) 
Example #14
Source File: testgraphplot.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_plot_simple_trimesh(self):
        plot = mpl_renderer.get_plot(self.trimesh)
        nodes = plot.handles['nodes']
        edges = plot.handles['edges']
        self.assertIsInstance(edges, LineCollection)
        self.assertEqual(np.asarray(nodes.get_offsets()), self.trimesh.nodes.array([0, 1]))
        self.assertEqual([p.vertices for p in edges.get_paths()],
                         [p.array() for p in self.trimesh._split_edgepaths.split()]) 
Example #15
Source File: _plotutils.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def convex_hull_plot_2d(hull, ax=None):
    """
    Plot the given convex hull diagram in 2-D

    Parameters
    ----------
    hull : scipy.spatial.ConvexHull instance
        Convex hull to plot
    ax : matplotlib.axes.Axes instance, optional
        Axes to plot on

    Returns
    -------
    fig : matplotlib.figure.Figure instance
        Figure for the plot

    See Also
    --------
    ConvexHull

    Notes
    -----
    Requires Matplotlib.

    """
    from matplotlib.collections import LineCollection

    if hull.points.shape[1] != 2:
        raise ValueError("Convex hull is not 2-D")

    ax.plot(hull.points[:,0], hull.points[:,1], 'o')
    line_segments = [hull.points[simplex] for simplex in hull.simplices]
    ax.add_collection(LineCollection(line_segments,
                                     colors='k',
                                     linestyle='solid'))
    _adjust_bounds(ax, hull.points)

    return ax.figure 
Example #16
Source File: geometry.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_artists(self, ax, plot_args, plot_kwargs):
        if 'c' in plot_kwargs:
            plot_kwargs['array'] = plot_kwargs.pop('c')
        if 'vmin' in plot_kwargs and 'vmax' in plot_kwargs:
            plot_kwargs['clim'] = plot_kwargs.pop('vmin'), plot_kwargs.pop('vmax')
        line_segments = LineCollection(*plot_args, **plot_kwargs)
        ax.add_collection(line_segments)
        return {'artist': line_segments} 
Example #17
Source File: graphs.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_artists(self, ax, plot_args, plot_kwargs):
        # Draw edges
        color_opts = ['c', 'cmap', 'vmin', 'vmax', 'norm']
        groups = [g for g in self._style_groups if g != 'edge']
        edge_opts = filter_styles(plot_kwargs, 'edge', groups, color_opts)
        if 'c' in edge_opts:
            edge_opts['array'] = edge_opts.pop('c')
        paths = plot_args['edges']
        if self.filled:
            coll = PolyCollection
            if 'colors' in edge_opts:
                edge_opts['facecolors'] = edge_opts.pop('colors')
        else:
            coll = LineCollection
        edgecolors = edge_opts.pop('edgecolors', None)
        edges = coll(paths, **edge_opts)
        if edgecolors is not None:
            edges.set_edgecolors(edgecolors)
        ax.add_collection(edges)

        # Draw nodes
        xs, ys = plot_args['nodes']
        groups = [g for g in self._style_groups if g != 'node']
        node_opts = filter_styles(plot_kwargs, 'node', groups)
        nodes = ax.scatter(xs, ys, **node_opts)

        return {'nodes': nodes, 'edges': edges} 
Example #18
Source File: chart.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_artists(self, ax, plot_args, plot_kwargs):
        if 'c' in plot_kwargs:
            plot_kwargs['array'] = plot_kwargs.pop('c')
        if 'vmin' in plot_kwargs and 'vmax' in plot_kwargs:
            plot_kwargs['clim'] = plot_kwargs.pop('vmin'), plot_kwargs.pop('vmax')
        line_segments = LineCollection(*plot_args, **plot_kwargs)
        ax.add_collection(line_segments)
        return {'artist': line_segments} 
Example #19
Source File: heatmap.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def init_artists(self, ax, plot_args, plot_kwargs):
        # Draw edges
        color_opts = ['c', 'cmap', 'vmin', 'vmax', 'norm', 'array']
        groups = [g for g in self._style_groups if g != 'annular']
        edge_opts = filter_styles(plot_kwargs, 'annular', groups)
        annuli = plot_args['annular']
        edge_opts.pop('interpolation', None)
        annuli = PatchCollection(annuli, transform=ax.transAxes, **edge_opts)
        ax.add_collection(annuli)

        artists = {'artist': annuli}

        paths = plot_args['xseparator']
        if paths:
            groups = [g for g in self._style_groups if g != 'xmarks']
            xmark_opts = filter_styles(plot_kwargs, 'xmarks', groups, color_opts)
            xmark_opts.pop('edgecolors', None)
            xseparators = LineCollection(paths, **xmark_opts)
            ax.add_collection(xseparators)
            artists['xseparator'] = xseparators

        paths = plot_args['yseparator']
        if paths:
            groups = [g for g in self._style_groups if g != 'ymarks']
            ymark_opts = filter_styles(plot_kwargs, 'ymarks', groups, color_opts)
            ymark_opts.pop('edgecolors', None)
            yseparators = PatchCollection(paths, facecolor='none',
                                          transform=ax.transAxes, **ymark_opts)
            ax.add_collection(yseparators)
            artists['yseparator'] = yseparators

        return artists 
Example #20
Source File: colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _add_solids(self, X, Y, C):
        '''
        Draw the colors using :meth:`~matplotlib.axes.Axes.pcolormesh`;
        optionally add separators.
        '''
        if self.orientation == 'vertical':
            args = (X, Y, C)
        else:
            args = (np.transpose(Y), np.transpose(X), np.transpose(C))
        kw = dict(cmap=self.cmap,
                  norm=self.norm,
                  alpha=self.alpha,
                  edgecolors='None')
        _log.debug('Setting pcolormesh')
        col = self.ax.pcolormesh(*args, **kw)
        # self.add_observer(col) # We should observe, not be observed...

        if self.solids is not None:
            self.solids.remove()
        self.solids = col
        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None
        if self.drawedges:
            linewidths = (0.5 * mpl.rcParams['axes.linewidth'],)
            self.dividers = collections.LineCollection(
                    self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=linewidths)
            self.ax.add_collection(self.dividers)
        elif len(self._y) >= self.n_rasterize:
            self.solids.set_rasterized(True) 
Example #21
Source File: parameters.py    From NEUCOGAR with GNU General Public License v2.0 5 votes vote down vote up
def plot_weights(weights_list, title="Neurons weights progress"):
    # Make a list of colors cycling through the rgbcmyk series.
    colors = [colorConverter.to_rgba(c) for c in ('k', 'r', 'g', 'b', 'c', 'y', 'm')]
    axes = pl.axes()
    ax4 = axes  # unpack the axes
    ncurves = 1
    offs = (0.0, 0.0)
    segs = []
    for i in range(ncurves):
        curve = weights_list
        segs.append(curve)

    col = collections.LineCollection(segs, offsets=offs)
    ax4.add_collection(col, autolim=True)
    col.set_color(colors)
    ax4.autoscale_view()
    ax4.set_title(title)
    ax4.set_xlabel('Time ms')
    ax4.set_ylabel('Weight pA')
    y_lim = 105.
    if y_lim:
        ax4.set_ylim(-5, y_lim)
    pl.savefig(f_name_gen('dopa-weights', is_image=True), format='png')
    # pl.show()

# =======
# DEVICES
# ======= 
Example #22
Source File: geom_segment.py    From plotnine with GNU General Public License v2.0 5 votes vote down vote up
def draw_group(data, panel_params, coord, ax, **params):
        data = coord.transform(data, panel_params)
        data['size'] *= SIZE_FACTOR
        color = to_rgba(data['color'], data['alpha'])

        # start point -> end point, sequence of xy points
        # from which line segments are created
        x = interleave(data['x'], data['xend'])
        y = interleave(data['y'], data['yend'])
        segments = make_line_segments(x, y, ispath=False)
        coll = mcoll.LineCollection(segments,
                                    edgecolor=color,
                                    linewidth=data['size'],
                                    linestyle=data['linetype'][0],
                                    zorder=params['zorder'])
        ax.add_collection(coll)

        if 'arrow' in params and params['arrow']:
            adata = pd.DataFrame(index=range(len(data)*2))
            idx = np.arange(1, len(data)+1)
            adata['group'] = np.hstack([idx, idx])
            adata['x'] = np.hstack([data['x'], data['xend']])
            adata['y'] = np.hstack([data['y'], data['yend']])
            other = ['color', 'alpha', 'size', 'linetype']
            for param in other:
                adata[param] = np.hstack([data[param], data[param]])

            params['arrow'].draw(
                adata, panel_params, coord, ax,
                params['zorder'], constant=False) 
Example #23
Source File: utils.py    From scvelo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_rug(x, height=0.03, color=None, ax=None, **kwargs):
    if ax is None:
        ax = pl.gca()
    x = np.asarray(x)

    transform = tx.blended_transform_factory(ax.transData, ax.transAxes)
    line_segs = np.column_stack(
        [np.repeat(x, 2), np.tile([0, height], len(x))]
    ).reshape([len(x), 2, 2])
    kwargs.update({"transform": transform, "color": color})
    ax.add_collection(LineCollection(line_segs, **kwargs))
    ax.autoscale_view(scalex=True, scaley=False) 
Example #24
Source File: core.py    From nelpy with MIT License 5 votes vote down vote up
def colorline(x, y, cmap=None, cm_range=(0, 0.7), **kwargs):
    """Colorline plots a trajectory of (x,y) points with a colormap"""

    # plt.plot(x, y, '-k', zorder=1)
    # plt.scatter(x, y, s=40, c=plt.cm.RdBu(np.linspace(0,1,40)), zorder=2, edgecolor='k')

    assert len(cm_range)==2, "cm_range must have (min, max)"
    assert len(x) == len(y), "x and y must have the same number of elements!"

    ax = kwargs.get('ax', plt.gca())
    lw = kwargs.get('lw', 2)
    if cmap is None:
        cmap=plt.cm.Blues_r

    t = np.linspace(cm_range[0], cm_range[1], len(x))

    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    lc = LineCollection(segments, cmap=cmap, norm=plt.Normalize(0, 1),
                        zorder=50)
    lc.set_array(t)
    lc.set_linewidth(lw)

    ax.add_collection(lc)

    return lc 
Example #25
Source File: isotonic_regression.py    From Machine-Learning-Algorithms-Second-Edition with MIT License 5 votes vote down vote up
def show_isotonic_regression_segments(X, Y, Yi, segments):
    lc = LineCollection(segments, zorder=0)
    lc.set_array(np.ones(len(Y)))
    lc.set_linewidths(0.5 * np.ones(nb_samples))

    fig, ax = plt.subplots(1, 1, figsize=(30, 25))

    ax.plot(X, Y, 'b.', markersize=8)
    ax.plot(X, Yi, 'g.-', markersize=8)
    ax.grid()
    ax.set_xlabel('X')
    ax.set_ylabel('Y')

    plt.show() 
Example #26
Source File: display.py    From global-divergences with MIT License 5 votes vote down vote up
def plot(self, axis, springs=True) :
        def contour_plot(img, color, nlines=15, zero=False) :
            levels = np.linspace(np.amin( img ), np.amax( img ), nlines)
            axis.contour(img, origin='lower', linewidths = 1., colors = color,
                        levels = levels, extent=coords[0:4]) 
            if zero :
                try : # Bold line for the zero contour line; throws a warning if no "0" is found
                    axis.contour(img, origin='lower', linewidths = 2., colors = color,
                                levels = (0.), extent=coords[0:4]) 
                except : pass

        contour_plot(self.a, "#E2C5C5")
        contour_plot(self.b, "#C8DFF9")

        # Springs
        if springs :
            springs_a = [ [s_i,t_i] for (s_i,t_i) in zip(self.x_i,self.xt_i)]
            springs_b = [ [s_j,t_j] for (s_j,t_j) in zip(self.y_j,self.yt_j)]
            seg_colors_a = [ (.8, .4, .4, .05) ] * len(self.x_i)
            seg_colors_b = [ (.4, .4, .8, .05) ] * len(self.y_j)
            
            line_segments = LineCollection(springs_b, linewidths=(1,), 
                                        colors=seg_colors_b, linestyle='solid')
            axis.add_collection(line_segments)
            
            line_segments = LineCollection(springs_a, linewidths=(1,), 
                                        colors=seg_colors_a, linestyle='solid')
            axis.add_collection(line_segments) 
Example #27
Source File: proj3d.py    From opticspy with MIT License 5 votes vote down vote up
def test_proj_draw_axes(M, s=1):
    import pylab
    xs, ys, zs = [0, s, 0, 0], [0, 0, s, 0], [0, 0, 0, s]
    txs, tys, tzs = proj_transform(xs, ys, zs, M)
    o, ax, ay, az = (txs[0], tys[0]), (txs[1], tys[1]), \
            (txs[2], tys[2]), (txs[3], tys[3])
    lines = [(o, ax), (o, ay), (o, az)]

    ax = pylab.gca()
    linec = LineCollection(lines)
    ax.add_collection(linec)
    for x, y, t in zip(txs, tys, ['o', 'x', 'y', 'z']):
        pylab.text(x, y, t) 
Example #28
Source File: axes3d.py    From opticspy with MIT License 5 votes vote down vote up
def add_collection3d(self, col, zs=0, zdir='z'):
        '''
        Add a 3D collection object to the plot.

        2D collection types are converted to a 3D version by
        modifying the object and adding z coordinate information.

        Supported are:
            - PolyCollection
            - LineColleciton
            - PatchCollection
        '''
        zvals = np.atleast_1d(zs)
        if len(zvals) > 0 :
            zsortval = min(zvals)
        else :
            zsortval = 0   # FIXME: Fairly arbitrary. Is there a better value?

        # FIXME: use issubclass() (although, then a 3D collection
        #       object would also pass.)  Maybe have a collection3d
        #       abstract class to test for and exclude?
        if type(col) is mcoll.PolyCollection:
            art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir)
            col.set_sort_zpos(zsortval)
        elif type(col) is mcoll.LineCollection:
            art3d.line_collection_2d_to_3d(col, zs=zs, zdir=zdir)
            col.set_sort_zpos(zsortval)
        elif type(col) is mcoll.PatchCollection:
            art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir)
            col.set_sort_zpos(zsortval)

        Axes.add_collection(self, col) 
Example #29
Source File: 6isotonic_regression.py    From Fundamentals-of-Machine-Learning-with-scikit-learn with MIT License 5 votes vote down vote up
def show_isotonic_regression_segments(X, Y, Yi, segments):
    lc = LineCollection(segments, zorder=0)
    lc.set_array(np.ones(len(Y)))
    lc.set_linewidths(0.5 * np.ones(nb_samples))

    fig, ax = plt.subplots(1, 1, figsize=(30, 25))

    ax.plot(X, Y, 'b.', markersize=8)
    ax.plot(X, Yi, 'g.-', markersize=8)
    ax.grid()
    ax.set_xlabel('X')
    ax.set_ylabel('Y')

    plt.show() 
Example #30
Source File: colorbar.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_lines(self, levels, colors, linewidths, erase=True):
        '''
        Draw lines on the colorbar.

        *colors* and *linewidths* must be scalars or
        sequences the same length as *levels*.

        Set *erase* to False to add lines without first
        removing any previously added lines.
        '''
        y = self._locate(levels)
        rtol = (self._y[-1] - self._y[0]) * 1e-10
        igood = (y < self._y[-1] + rtol) & (y > self._y[0] - rtol)
        y = y[igood]
        if cbook.iterable(colors):
            colors = np.asarray(colors)[igood]
        if cbook.iterable(linewidths):
            linewidths = np.asarray(linewidths)[igood]
        X, Y = np.meshgrid([self._y[0], self._y[-1]], y)
        if self.orientation == 'vertical':
            xy = np.stack([X, Y], axis=-1)
        else:
            xy = np.stack([Y, X], axis=-1)
        col = collections.LineCollection(xy, linewidths=linewidths)

        if erase and self.lines:
            for lc in self.lines:
                lc.remove()
            self.lines = []
        self.lines.append(col)
        col.set_color(colors)
        self.ax.add_collection(col)
        self.stale = True