python类LineCollection()的实例源码

guide_colorbar.py 文件源码 项目:plotnine 作者: has2k1 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
cmon_plt.py 文件源码 项目:brainpipe 作者: EtienneCmb 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __new__(self, ax, y, x=None, color=None, cmap='inferno', pltargs={}, **kwargs):
        # Check inputs :
        y = np.ravel(y)
        if x is None:
            x = np.arange(len(y))
        else:
            x = np.ravel(x)
            if len(y) != len(x):
                raise ValueError('x and y must have the same length')
        if color is None:
            color = np.arange(len(y))

        # Create segments:
        xy = np.array([x, y]).T[..., np.newaxis].reshape(-1, 1, 2)
        segments = np.concatenate((xy[0:-1, :], xy[1::]), axis=1)
        lc = LineCollection(segments, cmap=cmap, **pltargs)
        lc.set_array(color)

        # Plot managment:
        ax.add_collection(lc)
        plt.axis('tight')
        _pltutils.__init__(self, ax, **kwargs)

        return plt.gca()
lddmm_theano.py 文件源码 项目:lddmm-ot 作者: jeanfeydy 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def plot(self, ax, color = 'rainbow', linewidth = 3) :
        "Simple display using a per-id color scheme."
        segs = self.segments()

        if color == 'rainbow' :   # rainbow color scheme to see pointwise displacements
            ncycles    = 5
            cNorm      = colors.Normalize(vmin=0, vmax=(len(segs)-1)/ncycles)
            scalarMap  = cm.ScalarMappable(norm=cNorm, cmap=plt.get_cmap('hsv') )
            seg_colors = [ scalarMap.to_rgba( i % ((len(segs)-1)/ncycles) ) 
                           for i in range(len(segs)) ]
        else :                    # uniform color
            seg_colors = [ color for i in range(len(segs)) ] 

        line_segments = LineCollection(segs, linewidths=(linewidth,), 
                                       colors=seg_colors, linestyle='solid')
        ax.add_collection(line_segments)
lddmm_pytorch.py 文件源码 项目:lddmm-ot 作者: jeanfeydy 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def plot(self, ax, color = 'rainbow', linewidth = 3) :
        "Simple display using a per-id color scheme."
        segs = self.segments()

        if color == 'rainbow' :   # rainbow color scheme to see pointwise displacements
            ncycles    = 5
            cNorm      = colors.Normalize(vmin=0, vmax=(len(segs)-1)/ncycles)
            scalarMap  = cm.ScalarMappable(norm=cNorm, cmap=plt.get_cmap('hsv') )
            seg_colors = [ scalarMap.to_rgba( i % ((len(segs)-1)/ncycles) ) 
                           for i in range(len(segs)) ]
        else :                    # uniform color
            seg_colors = [ color for i in range(len(segs)) ] 

        line_segments = LineCollection(segs, linewidths=(linewidth,), 
                                       colors=seg_colors, linestyle='solid')
        ax.add_collection(line_segments)
curve.py 文件源码 项目:lddmm-ot 作者: jeanfeydy 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def plot(self, ax, color = 'rainbow', linewidth = 3) :
        "Simple display using a per-id color scheme."
        segs = self.segments()

        if color == 'rainbow' :   # rainbow color scheme to see pointwise displacements
            ncycles    = 5
            cNorm      = colors.Normalize(vmin=0, vmax=(len(segs)-1)/ncycles)
            scalarMap  = cm.ScalarMappable(norm=cNorm, cmap=plt.get_cmap('hsv') )
            seg_colors = [ scalarMap.to_rgba( i % ((len(segs)-1)/ncycles) ) 
                           for i in range(len(segs)) ]
        else :                    # uniform color
            seg_colors = [ color for i in range(len(segs)) ] 

        line_segments = LineCollection(segs, linewidths=(linewidth,), 
                                       colors=seg_colors, linestyle='solid')
        ax.add_collection(line_segments)
image_to_laser_moves.py 文件源码 项目:OpenFL 作者: Formlabs 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def plotResults(result):
    from pylab import figure, hold, show
    from matplotlib import collections  as mc
    figure()
    hold(True)
    lines = []
    mWs = []
    for seg_i in range(1, len(result)):
        lines.append([result[seg_i-1][1:3], result[seg_i][1:3]])
        mWs.append(result[seg_i][3])

    norm = mpl.colors.Normalize(vmin=0, vmax=150)
    colorMapper = cm.ScalarMappable(norm=norm, cmap=cm.jet)
    lc = mc.LineCollection(lines, linewidths=2, colors=colorMapper.to_rgba(mWs))
    ax = gca()
    ax.add_collection(lc)
    ax.autoscale()
    ax.margins(0.1)
    ax.axis('equal')

    #plot(result[:,2], result[:,1])
    #scatter(result[:,2], result[:,1], c=result[:,3],vmin=0, vmax=150)
    #colorbar(colorMapper)
    show()
regriptppass.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plotGraph(self, pltax, offset = [0,0]):
        """

        :param pltax:
        :param offset: where to plot the graph
        :return:
        """

        # add offset
        for i in self.gnodesplotpos.keys():
            self.gnodesplotpos[i] = map(add, self.gnodesplotpos[i], offset)

        transitedges = []
        transferedges = []
        for nid0, nid1, reggedgedata in self.regg.edges(data=True):
            if reggedgedata['edgetype'] is 'transit':
                transitedges.append([self.gnodesplotpos[nid0][:2], self.gnodesplotpos[nid1][:2]])
            if reggedgedata['edgetype'] is 'transfer':
                transferedges.append([self.gnodesplotpos[nid0][:2], self.gnodesplotpos[nid1][:2]])
        transitec = mc.LineCollection(transitedges, colors=[0,1,1,1], linewidths=1)
        transferec = mc.LineCollection(transferedges, colors=[0,0,0,.1], linewidths=1)
        pltax.add_collection(transferec)
        pltax.add_collection(transitec)
regriptppass.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __plotEnds(self, pltax):
        transitedges = []
        transferedges = []
        for nid0, nid1, reggedgedata in self.graphtpp.regg.edges(data=True):
            if nid0.startswith('end'):
                pos0 = self.gnodesplotpos[nid0][:2]
            else:
                pos0 = self.graphtpp.gnodesplotpos[nid0][:2]
            if nid1.startswith('end'):
                pos1 = self.gnodesplotpos[nid1][:2]
            else:
                pos1 = self.graphtpp.gnodesplotpos[nid1][:2]
            if (reggedgedata['edgetype'] == 'endtransit'):
                transitedges.append([pos0, pos1])
            elif (reggedgedata['edgetype'] is 'endtransfer'):
                transferedges.append([pos0, pos1])
        transitec = mc.LineCollection(transitedges, colors = [.5,0,0,.3], linewidths = 1)
        transferec = mc.LineCollection(transferedges, colors = [1,0,0,.3], linewidths = 1)
        pltax.add_collection(transferec)
        pltax.add_collection(transitec)
regriptppass.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plotshortestpath(self, pltax, id=0):
        """
        plot the shortest path

        :param id:
        :return:
        """

        for i,path in enumerate(self.directshortestpaths):
            if i is id:
                pathedges = []
                pathlength = len(path)
                for pnidx in range(pathlength-1):
                    nid0 = path[pnidx]
                    nid1 = path[pnidx+1]
                    pathedges.append([self.composedgnodesplotpos[nid0][:2], self.composedgnodesplotpos[nid1][:2]])
                pathedgesec = mc.LineCollection(pathedges, colors=[0, 1, 0, 1], linewidths=5)

                pltax.add_collection(pathedgesec)
regriptppass_backup.py 文件源码 项目:pyhiro 作者: wanweiwei07 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __plotEnds(self, pltax, endname = 'end'):
        transitedges = []
        transferedges = []
        for nid0, nid1, reggedgedata in self.graphtpp.regg.edges(data=True):
            if nid0.startswith('end'):
                pos0 = self.gnodesplotpos[nid0][:2]
            else:
                pos0 = self.graphtpp.gnodesplotpos[nid0][:2]
            if nid1.startswith('end'):
                pos1 = self.gnodesplotpos[nid1][:2]
            else:
                pos1 = self.graphtpp.gnodesplotpos[nid1][:2]
            if (reggedgedata['edgetype'] == 'endtransit'):
                transitedges.append([pos0, pos1])
            elif (reggedgedata['edgetype'] is 'endtransfer'):
                transferedges.append([pos0, pos1])
        transitec = mc.LineCollection(transitedges, colors = [.5,0,0,.3], linewidths = 1)
        transferec = mc.LineCollection(transferedges, colors = [1,0,0,.3], linewidths = 1)
        pltax.add_collection(transferec)
        pltax.add_collection(transitec)
faampy_flight_analysis_example.py 文件源码 项目:faampy 作者: ncasuk 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def colorline(x, y, z=None, cmap=plt.get_cmap('copper'),
              norm=plt.Normalize(0.0, 1.0), linewidth=3, alpha=1.0):
    """
    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
    """

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

    z = np.asarray(z)

    segments = make_segments(x, y)
    lc = LineCollection(segments, array=z, cmap=cmap, norm=norm, \
                        linewidth=linewidth, alpha=alpha)
    ax = plt.gca()
    ax.add_collection(lc)
    return lc
models.py 文件源码 项目:siHMM 作者: Ardavans 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _plot_stateseq_data_values(self,s,ax,state_colors,plot_slice,update):
        from matplotlib.collections import LineCollection
        from pyhsmm.util.general import AR_striding, rle

        data = s.data[plot_slice]
        stateseq = s.stateseq[plot_slice]

        colorseq = np.tile(np.array([state_colors[state] for state in stateseq[:-1]]),data.shape[1])

        if update and hasattr(s,'_data_lc'):
            s._data_lc.set_array(colorseq)
        else:
            ts = np.arange(len(stateseq))
            segments = np.vstack(
                [AR_striding(np.hstack((ts[:,None], scalarseq[:,None])),1).reshape(-1,2,2)
                    for scalarseq in data.T])
            lc = s._data_lc = LineCollection(segments)
            lc.set_array(colorseq)
            lc.set_linewidth(0.5)
            ax.add_collection(lc)

        return s._data_lc
rnn_curve_predict.py 文件源码 项目:rnn-tutorial-curve-predict 作者: timctho 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def create_curve():
    # Create the curve which we want the RNN to learn
    plt.ion()
    fig = plt.figure(figsize=(10, 10))
    ax = plt.gca()
    r = np.arange(0, .34, 0.001)
    n_points = len(r)
    theta = 45 * np.pi * r
    x_offset, y_offset = .5, .5
    y_curve_points = 1.4 * r * np.sin(theta) + y_offset
    x_curve_points = r * np.cos(theta) + x_offset
    curve = list(zip(x_curve_points, y_curve_points))
    collection = LineCollection([curve], colors='k')
    ax.add_collection(collection)
    return ax, n_points, x_curve_points, y_curve_points
util.py 文件源码 项目:prysm 作者: brandondube 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def make_segments(x, y):
    '''
    Create list of line segments from x and y coordinates, in the correct format for LineCollection:
    an array of the form   numlines x (points per line) x 2 (x and y) array
    '''

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

    return segments
util.py 文件源码 项目:prysm 作者: brandondube 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def colorline(x, y, z=None, cmap=plt.get_cmap('Spectral_r'), cmin=None, cmax=None, lw=3):
    '''
    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
    '''

    cmap = copy(cmap)
    cmap.set_over('k')
    cmap.set_under('k')

    # 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)
    return LineCollection(segments, array=z, cmap=cmap, norm=plt.Normalize(vmin=cmin, vmax=cmax), linewidth=lw)
geom_segment.py 文件源码 项目:plotnine 作者: has2k1 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
geom_path.py 文件源码 项目:plotnine 作者: has2k1 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _draw_segments(data, ax, **params):
    """
    Draw independent line segments between all the
    points
    """
    color = to_rgba(data['color'], data['alpha'])
    # All we do is line-up all the points in a group
    # into segments, all in a single list.
    # Along the way the other parameters are put in
    # sequences accordingly
    indices = []  # for attributes of starting point of each segment
    segments = []
    for _, df in data.groupby('group'):
        idx = df.index
        indices.extend(idx[:-1])  # One line from two points
        x = data['x'].iloc[idx]
        y = data['y'].iloc[idx]
        segments.append(make_line_segments(x, y, ispath=True))

    segments = np.vstack(segments)

    if color is None:
        edgecolor = color
    else:
        edgecolor = [color[i] for i in indices]

    linewidth = data.loc[indices, 'size']
    linestyle = data.loc[indices, 'linetype']

    coll = mcoll.LineCollection(segments,
                                edgecolor=edgecolor,
                                linewidth=linewidth,
                                linestyle=linestyle,
                                zorder=params['zorder'])
    ax.add_collection(coll)
bands_Cu.py 文件源码 项目:bandstructureplots 作者: gVallverdu 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def rgbline(ax, k, e, red, green, blue, alpha=1.):
    # creation of segments based on
    # http://nbviewer.ipython.org/urls/raw.github.com/dpsanders/matplotlib-examples/master/colorline.ipynb
    pts = np.array([k, e]).T.reshape(-1, 1, 2)
    seg = np.concatenate([pts[:-1], pts[1:]], axis=1)

    nseg = len(k) - 1
    r = [0.5 * (red[i] + red[i + 1]) for i in range(nseg)]
    g = [0.5 * (green[i] + green[i + 1]) for i in range(nseg)]
    b = [0.5 * (blue[i] + blue[i + 1]) for i in range(nseg)]
    a = np.ones(nseg, np.float) * alpha
    lc = LineCollection(seg, colors=list(zip(r, g, b, a)), linewidth=2)
    ax.add_collection(lc)
bands_Si.py 文件源码 项目:bandstructureplots 作者: gVallverdu 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def rgbline(ax, k, e, red, green, blue, alpha=1.):
    # creation of segments based on
    # http://nbviewer.ipython.org/urls/raw.github.com/dpsanders/matplotlib-examples/master/colorline.ipynb
    pts = np.array([k, e]).T.reshape(-1, 1, 2)
    seg = np.concatenate([pts[:-1], pts[1:]], axis=1)

    nseg = len(k) - 1
    r = [0.5 * (red[i] + red[i + 1]) for i in range(nseg)]
    g = [0.5 * (green[i] + green[i + 1]) for i in range(nseg)]
    b = [0.5 * (blue[i] + blue[i + 1]) for i in range(nseg)]
    a = np.ones(nseg, np.float) * alpha
    lc = LineCollection(seg, colors=list(zip(r, g, b, a)), linewidth=2)
    ax.add_collection(lc)
graphene.py 文件源码 项目:bandstructureplots 作者: gVallverdu 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def rgbline(ax, k, e, red, green, blue, alpha=1.):
    # creation of segments based on
    # http://nbviewer.ipython.org/urls/raw.github.com/dpsanders/matplotlib-examples/master/colorline.ipynb
    pts = np.array([k, e]).T.reshape(-1, 1, 2)
    seg = np.concatenate([pts[:-1], pts[1:]], axis=1)

    nseg = len(k) - 1
    r = [0.5 * (red[i] + red[i + 1]) for i in range(nseg)]
    g = [0.5 * (green[i] + green[i + 1]) for i in range(nseg)]
    b = [0.5 * (blue[i] + blue[i + 1]) for i in range(nseg)]
    a = np.ones(nseg, np.float) * alpha
    lc = LineCollection(seg, colors=list(zip(r, g, b, a)), linewidth=2)
    ax.add_collection(lc)
plot_figures.py 文件源码 项目:IDNNs 作者: ravidziv 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def update_line(num, print_loss, data, axes, epochsInds, test_error, test_data, epochs_bins, loss_train_data, loss_test_data, colors,
                font_size = 18, axis_font=16, x_lim = [0,12.2], y_lim=[0, 1.08], x_ticks = [], y_ticks = []):
    """Update the figure of the infomration plane for the movie"""
    #Print the line between the points
    cmap = ListedColormap(LAYERS_COLORS)
    segs = []
    for i in range(0, data.shape[1]):
        x = data[0, i, num, :]
        y = data[1, i, num, :]
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segs.append(np.concatenate([points[:-1], points[1:]], axis=1))
    segs = np.array(segs).reshape(-1, 2, 2)
    axes[0].clear()
    if len(axes)>1:
        axes[1].clear()
    lc = LineCollection(segs, cmap=cmap, linestyles='solid',linewidths = 0.3, alpha = 0.6)
    lc.set_array(np.arange(0,5))
    #Print the points
    for layer_num in range(data.shape[3]):
        axes[0].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color = colors[layer_num], s = 35,edgecolors = 'black',alpha = 0.85)
    axes[1].plot(epochsInds[:num], 1 - np.mean(test_error[:, :num], axis=0), color ='r')

    title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num])
    utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True,
                     x_label='$I(X;T)$', y_label='$I(T;Y)$')
    title_str = 'Precision as function of the epochs'
    utils.adjustAxes(axes[1], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True,
                     x_label='# Epochs', y_label='Precision')
core.py 文件源码 项目:nelpy 作者: nelpy 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
6isotonic_regression.py 文件源码 项目:Machine-Learning-Algorithms 作者: PacktPublishing 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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()
viz.py 文件源码 项目:autoreject 作者: autoreject 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _update_channels_epochs(event, params):
    """Function for changing the amount of channels and epochs per view."""
    from matplotlib.collections import LineCollection
    # Channels
    n_channels = int(np.around(params['channel_slider'].val))
    offset = params['ax'].get_ylim()[0] / n_channels
    params['offsets'] = np.arange(n_channels) * offset + (offset / 2.)
    while len(params['lines']) > n_channels:
        params['ax'].collections.pop()
        params['lines'].pop()
    while len(params['lines']) < n_channels:
        lc = LineCollection(list(), linewidths=0.5, antialiased=False,
                            zorder=3, picker=3.)
        params['ax'].add_collection(lc)
        params['lines'].append(lc)
    params['ax'].set_yticks(params['offsets'])
    params['vsel_patch'].set_height(n_channels)
    params['n_channels'] = n_channels

    # Epochs
    n_epochs = int(np.around(params['epoch_slider'].val))
    n_times = len(params['epochs'].times)
    ticks = params['epoch_times'] + 0.5 * n_times
    params['ax2'].set_xticks(ticks[:n_epochs])
    params['n_epochs'] = n_epochs
    params['duration'] = n_times * n_epochs
    params['hsel_patch'].set_width(params['duration'])
    params['data'] = np.zeros((len(params['data']), params['duration']))
    if params['t_start'] + n_times * n_epochs > len(params['times']):
        params['t_start'] = len(params['times']) - n_times * n_epochs
        params['hsel_patch'].set_x(params['t_start'])
    params['plot_update_proj_callback'](params)
mplots.py 文件源码 项目:quantdigger 作者: andyzsf 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def plot(self, widget, c=None, lw=2):
        useAA = 0,  # use tuple here
        signal = LineCollection(self.signal, colors=c, linewidths=lw,
                                antialiaseds=useAA)
        widget.add_collection(signal)
mplots.py 文件源码 项目:quantdigger 作者: andyzsf 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plot(self, widget, lw=2):
        useAA = 0,  # use tuple here
        signal = LineCollection(self.signal, colors=self.colors, linewidths=lw,
                                antialiaseds=useAA)
        widget.add_collection(signal)
colorbar.py 文件源码 项目:PaleoView 作者: GlobalEcologyLab 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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')
        # Save, set, and restore hold state to keep pcolor from
        # clearing the axes. Ordinarily this will not be needed,
        # since the axes object should already have hold set.
        _hold = self.ax.ishold()
        self.ax.hold(True)
#-----------------------------------------------
        col = self.ax.pcolor(*args, **kw) # was pcolormesh
#-----------------------------------------------
        self.ax.hold(_hold)
        #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)
colorbar.py 文件源码 项目:PaleoView 作者: GlobalEcologyLab 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
        igood = (y < 1.001) & (y > -0.001)
        y = y[igood]
        if cbook.iterable(colors):
            colors = np.asarray(colors)[igood]
        if cbook.iterable(linewidths):
            linewidths = np.asarray(linewidths)[igood]
        N = len(y)
        x = np.array([0.0, 1.0])
        X, Y = np.meshgrid(x, y)
        if self.orientation == 'vertical':
            xy = [zip(X[i], Y[i]) for i in xrange(N)]
        else:
            xy = [zip(Y[i], X[i]) for i in xrange(N)]
        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)
__init__.py 文件源码 项目:PaleoView 作者: GlobalEcologyLab 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def drawcoastlines(self,linewidth=1.,linestyle='solid',color='k',antialiased=1,ax=None,zorder=None):
        """
        Draw coastlines.

        .. tabularcolumns:: |l|L|

        ==============   ====================================================
        Keyword          Description
        ==============   ====================================================
        linewidth        coastline width (default 1.)
        linestyle        coastline linestyle (default solid)
        color            coastline color (default black)
        antialiased      antialiasing switch for coastlines (default True).
        ax               axes instance (overrides default axes instance)
        zorder           sets the zorder for the coastlines (if not specified,
                         uses default zorder for
                         matplotlib.patches.LineCollections).
        ==============   ====================================================

        returns a matplotlib.patches.LineCollection object.
        """
        if self.resolution is None:
            raise AttributeError('there are no boundary datasets associated with this Basemap instance')
        # get current axes instance (if none specified).
        ax = ax or self._check_ax()
        coastlines = LineCollection(self.coastsegs,antialiaseds=(antialiased,))
        coastlines.set_color(color)
        coastlines.set_linestyle(linestyle)
        coastlines.set_linewidth(linewidth)
        coastlines.set_label('_nolabel_')
        if zorder is not None:
            coastlines.set_zorder(zorder)
        # clip coastlines for round polar plots.
        if self.round: coastlines,c = self._clipcircle(ax,coastlines)
        ax.add_collection(coastlines)
        # set axes limits to fit map region.
        self.set_axes_limits(ax=ax)
        return coastlines
__init__.py 文件源码 项目:PaleoView 作者: GlobalEcologyLab 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def drawcounties(self,linewidth=0.1,linestyle='solid',color='k',antialiased=1,
                     ax=None,zorder=None,drawbounds=False):
        """
        Draw county boundaries in US. The county boundary shapefile
        originates with the NOAA Coastal Geospatial Data Project
        (http://coastalgeospatial.noaa.gov/data_gis.html).

        .. tabularcolumns:: |l|L|

        ==============   ====================================================
        Keyword          Description
        ==============   ====================================================
        linewidth        county boundary line width (default 0.1)
        linestyle        coastline linestyle (default solid)
        color            county boundary line color (default black)
        antialiased      antialiasing switch for county boundaries
                         (default True).
        ax               axes instance (overrides default axes instance)
        zorder           sets the zorder for the county boundaries (if not
                         specified, uses default zorder for
                         matplotlib.patches.LineCollections).
        ==============   ====================================================

        returns a matplotlib.patches.LineCollection object.
        """
        ax = ax or self._check_ax()
        gis_file = os.path.join(basemap_datadir,'UScounties')
        county_info = self.readshapefile(gis_file,'counties',\
                      default_encoding='latin-1',drawbounds=drawbounds)
        counties = [coords for coords in self.counties]
        counties = LineCollection(counties)
        counties.set_linestyle(linestyle)
        counties.set_linewidth(linewidth)
        counties.set_color(color)
        counties.set_label('counties')
        if zorder:
            counties.set_zorder(zorder)
        ax.add_collection(counties)
        return counties


问题


面经


文章

微信
公众号

扫码关注公众号