当前位置: 首页>>代码示例>>Python>>正文


Python LineCollection.set_array方法代码示例

本文整理汇总了Python中matplotlib.collections.LineCollection.set_array方法的典型用法代码示例。如果您正苦于以下问题:Python LineCollection.set_array方法的具体用法?Python LineCollection.set_array怎么用?Python LineCollection.set_array使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.collections.LineCollection的用法示例。


在下文中一共展示了LineCollection.set_array方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _draw_segments

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def _draw_segments(ax, x, y, state, cmap, norm, lc_kwargs):
    """
    helper function to turn boundary edges into the input LineCollection
    expects.

    Parameters
    ----------
    ax : Axes
       The axes to draw to

    x, y, state : array
       The x edges, the y values and the state of each region

    cmap : matplotlib.colors.Colormap
       The color map to use

    norm : matplotlib.ticker.Norm
       The norm to use with the color map

    lc_kwargs : dict
       kwargs to pass through to LineCollection
    """

    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=norm, **lc_kwargs)
    lc.set_array(state)

    ax.add_collection(lc)
    return lc
开发者ID:CJ-Wright,项目名称:xray-vision,代码行数:32,代码来源:misc.py

示例2: __plot_all

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
    def __plot_all(self):
        total = len(self.data)
        count = 0.0
        for timeStamp in self.data:
            if len(self.data[timeStamp]) < 2:
                self.parent.threadPlot = None
                return None, None

            if self.fade:
                alpha = (total - count) / total
            else:
                alpha = 1

            data = self.data[timeStamp].items()
            peakF, peakL = self.extent.get_peak_fl()

            segments, levels = self.__create_segments(data)
            lc = LineCollection(segments)
            lc.set_array(numpy.array(levels))
            lc.set_norm(self.__get_norm(self.autoL, self.extent))
            lc.set_cmap(self.colourMap)
            lc.set_linewidth(self.lineWidth)
            lc.set_gid('plot')
            lc.set_alpha(alpha)
            self.axes.add_collection(lc)
            count += 1

        return peakF, peakL
开发者ID:thatchristoph,项目名称:RTLSDR-Scanner,代码行数:30,代码来源:plot_line.py

示例3: gradient

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
    def gradient(figure_object, axis_object, xs, ys, start_year, TWP_length, cmap, key_count):
        """Based on http://matplotlib.org/examples/pylab_examples/multicolored_line.html
        and http://stackoverflow.com/questions/19132402/set-a-colormap-under-a-graph
        """
        from matplotlib.collections import LineCollection

        # plot a color_map line fading to white
        points = np.array([xs, ys]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments, cmap=plt.get_cmap('gray'), norm=plt.Normalize(start_year, start_year+TWP_length),
                            linewidth=0.2, zorder=1)   # norm sets the color min:max range
        lc.set_array(np.array(xs))
        axis_object.add_collection(lc)

        # add fading color_map fill as well
        xs.append(max(xs))
        xs.append(min(xs))
        ys.append(0)
        ys.append(0)
        poly, = axis_object.fill(xs, ys, facecolor='none', edgecolor='none')
        img_data = np.arange(0, 100, 1)
        img_data = img_data.reshape(1, img_data.size)
        im = axis_object.imshow(img_data, aspect='auto', origin='lower', cmap=plt.get_cmap(cmap),
                                extent=[start_year+TWP_length, start_year, 1000, -1000], vmin=0., vmax=100., zorder=-(start_year+1)*key_count)
        im.set_clip_path(poly)
开发者ID:johnlfield,项目名称:Forest_dynamics,代码行数:27,代码来源:LCA.py

示例4: draw_edges

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def draw_edges(tree, steiner_pos, diams=None, fig=None, ax=None, lim=None,
               colorbar=True):
    '''Draw edges with given positions.'''
    if fig is None:
        fig, ax = new_fig()
    if lim is None:
        lim = diam_min, diam_max

    pos = merge_pos(tree, steiner_pos)
    nodes = tree.get_nodes()
    arcs = tree.get_arcs()
    x = np.array([pos[n][0] for n in nodes])
    y = np.array([pos[n][1] for n in nodes])

    segments = [(pos[u], pos[v]) for (u,v) in arcs]

    if diams is None:
        lines = LineCollection(segments, colors='k', zorder=1)
    else:
        diams = np.array([diams[a] for a in arcs])
        lw = 7*diams + 1
        lines = LineCollection(segments, linewidths=lw, zorder=1)
        # set colors
        lines.set_array(diams)
        lines.set_cmap(_diam_cmap)
        lines.set_clim(*lim)
        if colorbar:
            plt.colorbar(lines, orientation='horizontal')
    ax.add_collection(lines)
开发者ID:hshlabs,项目名称:geonet,代码行数:31,代码来源:visual.py

示例5: colorbar_legend

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def colorbar_legend(ax, values, cmap, vis=True):
    """
    Add a vertical colorbar legend to a plot
    """
    x_range = ax.get_xlim()[1]-ax.get_xlim()[0]
    y_range = ax.get_ylim()[1]-ax.get_ylim()[0]

    x = [ax.get_xlim()[0]+x_range*0.05]
    y = [ax.get_ylim()[1]-(y_range * 0.25), ax.get_ylim()[1]-(y_range*0.05)]

    segs = []
    vals=[]
    p = (x[0], y[0]+((y[1]-y[0])/256.0))
    for i in range(2, 257):
        n = (x[0], y[0]+((y[1]-y[0])/256.0)*i)
        segs.append((p, n))
        p = segs[-1][-1]
        vals.append(min(values)+((max(values)-min(values))/256.0)*(i-1))
    lcbar =  LineCollection(segs, cmap=cmap, lw=15)
    lcbar.set_visible(vis)
    lcbar.set_array(np.array(vals))
    ax.add_collection(lcbar)
    lcbar.set_zorder(1)


    minlab = str(min(values))[:6]
    maxlab = str(max(values))[:6]

    ax.text(x[0]+x_range*.02, y[0], minlab, verticalalignment="bottom", visible=vis)
    ax.text(x[0]+x_range*.02, y[1], maxlab, verticalalignment="top", visible=vis)
开发者ID:ChriZiegler,项目名称:ivy,代码行数:32,代码来源:layers.py

示例6: __init__

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
class Visualize:
    def __init__(self, v, t, e, fig, win, axesLimit=[-3,3.5,-2,2]):
        self.e = e.copy()
        self.p = [Polygon(v[ti]) for ti in t]
        self.p = PatchCollection(self.p, edgecolors='none')
        self.l = LineCollection(v[e[:,:2]])

        win = win or fig.canvas.manager.window
        if fig is None: fig = gcf()
        fig.clf()
        ax = fig.add_axes([0.02,0.02,.98,.98])
        ax.axis('scaled')
        ax.axis(axesLimit)
        ax.set_autoscale_on(False)
        self.axis, self.fig, self.win = ax, fig, win

        ax.add_collection(self.p)
        ax.add_collection(self.l)
        # ax.add_collection(self.l1)
        # ax.add_collection(self.l2)

    def update(self, title, phi):
        norm = Normalize(phi.min(), phi.max())
        self.p.set_norm(norm)
        self.l.set_norm(norm)
        self.p.set_array(phi)
        self.l.set_array(phi[self.e[:,2:]].mean(1))
        if not self.__dict__.has_key('colorbar'):
            self.colorbar = self.fig.colorbar(self.p)
        self.win.set_title(title)
        #self.fig.canvas.set_window_title(title)
        self.fig.canvas.draw()
开发者ID:gomezstevena,项目名称:x-wind,代码行数:34,代码来源:meshVisualize.py

示例7: update_line

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
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')
开发者ID:HounD,项目名称:IDNNs,代码行数:30,代码来源:plot_figures.py

示例8: colorline

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def colorline(ax, x,y,z,linewidth=1, colormap='jet', norm=None, zorder=1, alpha=1, linestyle='solid'):
        cmap = plt.get_cmap(colormap)
        
        if type(linewidth) is list or type(linewidth) is np.array or type(linewidth) is np.ndarray:
            linewidths = linewidth
        else:
            linewidths = np.ones_like(z)*linewidth
        
        if norm is None:
            norm = plt.Normalize(np.min(z), np.max(z))
        else:
            norm = plt.Normalize(norm[0], norm[1])
        
        '''
        if self.hide_colorbar is False:
            if self.cb is None:
                self.cb = matplotlib.colorbar.ColorbarBase(self.ax1, cmap=cmap, norm=norm, orientation='vertical', boundaries=None)
        '''
            
        # Create a set of line segments so that we can color them individually
        # This creates the points as a N x 1 x 2 array so that we can stack points
        # together easily to get the segments. The segments array for line collection
        # needs to be numlines x points per line x 2 (x and y)
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        
        # Create the line collection object, setting the colormapping parameters.
        # Have to set the actual values used for colormapping separately.
        lc = LineCollection(segments, linewidths=linewidths, cmap=cmap, norm=norm, zorder=zorder, alpha=alpha, linestyles=linestyle )
        lc.set_array(z)
        lc.set_linewidth(linewidth)
        
        ax.add_collection(lc)
开发者ID:alexlib,项目名称:OdorPackets,代码行数:35,代码来源:floris_plot_lib.py

示例9: plot_Kiel_diagram

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def plot_Kiel_diagram(starl):
    """
    Plot Kiel diagram.
    """
    x = starl['temperature']
    y = starl['g']
    age = starl['age']/1e6
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    
    cmap = pl.cm.spectral
    norm = pl.Normalize(age.min(), age.max())
    lc = LineCollection(segments, cmap=cmap,norm=norm)
    lc.set_array(age)
    lc.set_linewidth(3)
    pl.gca().add_collection(lc)
    pl.xlim(x.max(), x.min())
    pl.ylim(y.max(), y.min())
    pl.xlabel('Effective temperature [K]')
    pl.ylabel('log(surface gravity [cm s$^{-2}$]) [dex]')
    
    ax0 = pl.gca()
    ax1 = pl.mpl.colorbar.make_axes(ax0)[0]
    norm = pl.mpl.colors.Normalize(age.min(), age.max())
    cb1 = pl.mpl.colorbar.ColorbarBase(ax1, cmap=cmap,
                                   norm=norm,orientation='vertical')
    cb1.set_label('Age [Myr]')
    pl.axes(ax0)
开发者ID:robinlombaert,项目名称:IvSPythonRepository,代码行数:30,代码来源:fileio.py

示例10: plot_file_color

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def plot_file_color(base, thin=True, start=0, size=14, save=False):
    conf, track, pegs = load(base)

    fig = pl.figure(figsize=(size,size*conf['top']/conf['wall']))

    track = track[start:]
    x = track[:,0];   y = track[:,1]
    t = np.linspace(0,1,x.shape[0])
    points = np.array([x,y]).transpose().reshape(-1,1,2)
    segs = np.concatenate([points[:-1],points[1:]],axis=1)
    lc = LineCollection(segs, linewidths=0.25, cmap=pl.cm.coolwarm)
    lc.set_array(t)
    pl.gca().add_collection(lc)

    #pl.scatter(x, y, c=np.arange(len(x)),linestyle='-',cmap=pl.cm.coolwarm)
    #pl.plot(track[-1000000:,0], track[-1000000:,1], '-', linewidth=0.0125, alpha=0.8)
    for peg in pegs:
        pl.gca().add_artist(pl.Circle(peg, conf['radius'], color='k', alpha=0.3))
    pl.xlim(0, conf['wall'])
    pl.ylim(0, conf['top'])
    pl.xticks([])
    pl.yticks([])
    pl.tight_layout()
    pl.show()
    if save:
        pl.savefig(base+".png", dpi=200)
开发者ID:mattbierbaum,项目名称:plinko,代码行数:28,代码来源:plotting.py

示例11: map_along_line

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def map_along_line(x, y, q, ax=None, cmap=None, norm=None,
            time=None, max_step=1., missing=np.nan,
            new_timebase=None,
            **kwargs):
    """Map some quantity q along x,y as a coloured line.
With time set, perform linear interpolation of x,y,q onto new_timebase
filling with missing, and with max_step."""

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

    if x.shape != y.shape:
        raise ValueError('Shape mismatch')
    if x.shape != q.shape:
        raise ValueError('Shape mismatch')

    if time is not None:
        if new_timebase is None:
            new_timebase = np.arange(time[0], time[-1], np.min(np.diff(time)))

        # Bit redundant
        x = interp_safe(new_timebase, time, x, max_step=max_step, missing=missing)
        y = interp_safe(new_timebase, time, y, max_step=max_step, missing=missing)
        q = interp_safe(new_timebase, time, q, max_step=max_step, missing=missing)

    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=norm, **kwargs)

    lc.set_array(q)
    plt.gca().add_collection(lc)

    return lc
开发者ID:irbdavid,项目名称:celsius,代码行数:35,代码来源:plot.py

示例12: hello

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def hello():

    rtimes, rt, rp = np.loadtxt("data/data.txt").T
    rtimes = map(datetime.datetime.fromtimestamp, rtimes)
    rtimes = matplotlib.dates.date2num(rtimes)
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    axis.xaxis_date()
    fig.autofmt_xdate()

    forecast_list = []
    for fname in glob.glob("data/forecast.*.txt"):
        stamp = fname.split(".")[1]
        times, tempa = np.loadtxt(fname).T
        times = map(datetime.datetime.fromtimestamp, times)
        times = matplotlib.dates.date2num(times)

        points = np.array([times, tempa]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments, cmap=plt.get_cmap("jet"),
                            norm=plt.Normalize(0, 1))
        lc.set_array(np.linspace(0,1,len(times)))
        lc.set_linewidth(1)
        axis.add_collection(lc)

        axis.plot_date(times, tempa, "-", linewidth=0)

    axis.plot_date(rtimes, rt, "-",linewidth=1, color="black")

    canvas = FigureCanvas(fig)
    output = StringIO.StringIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
开发者ID:jkfurtney,项目名称:forecast_check,代码行数:37,代码来源:flaskapp.py

示例13: d3

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
def d3():
    rtimes, rt, rp = np.loadtxt("data/data.txt").T
    mask = np.logical_and(rtimes>1391000000, rtimes<1393000000)
    rtimes = rtimes[mask]
    rt = rt[mask]
    rtimes = map(datetime.datetime.fromtimestamp, rtimes)
    rtimes = matplotlib.dates.date2num(rtimes)
    fig, axis = plt.subplots()

    axis.xaxis_date()
    fig.autofmt_xdate()
    axis.plot_date(rtimes, rt, "-",linewidth=3, color="black")

    forecast_list = []
    for fname in glob.glob("data/forecast.1391*.txt"):
        stamp = fname.split(".")[1]
        times, tempa = np.loadtxt(fname).T
        times = map(datetime.datetime.fromtimestamp, times)
        times = matplotlib.dates.date2num(times)

        points = np.array([times, tempa]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments, cmap=plt.get_cmap("jet"),
                            norm=plt.Normalize(0, 1))
        lc.set_array(np.linspace(0,1,len(times)))
        lc.set_linewidth(1)
        axis.add_collection(lc)

        axis.plot_date(times, tempa, "-", linewidth=2)



    return fig_to_html(fig)
开发者ID:jkfurtney,项目名称:forecast_check,代码行数:35,代码来源:flaskapp.py

示例14: get_figures

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
 def get_figures(self):
     from matplotlib.collections import LineCollection
     figs = []
     ys = [(1.0/self.PROCS_PER_WINDOW.value)*(i+1) for i in range(self.PROCS_PER_WINDOW.value)]
     all_xs = []
     for rad1, procs in self.rad1_to_procs.iteritems():
         windows = get_procedure_windows(procs, self.PROCS_PER_WINDOW.value,
                                self.STEP_SIZE.value)
         all_xs = []
         for window in windows:
             all_xs.append([p.fluoro for p in window])
         #the matplotlib part
         fig = plt.figure()
         ax = plt.gca()
         ax.set_xlim(0,10)
         ax.set_ylim(0,1)
         line_segments= LineCollection([zip(xs,ys) for xs in all_xs])
         line_segments.set_array(np.array(range(len(all_xs))))
         ax.add_collection(line_segments)
         plt.title(rad1)
         plt.xlabel("Fluoro Time")
         plt.ylabel("Fraction of Procedures Below Fluoro Time")
         colorbar = fig.colorbar(line_segments, ticks = range(len(windows)))#ticks = ?
         colorbar.set_ticklabels([str(window[0].dos_start) for window in windows])
         colorbar.set_label("Window Start Date")
         figs.append(fig)
     return figs
开发者ID:KirovskiXVI,项目名称:dicom-sr-qi,代码行数:29,代码来源:operator_improvement_surface.py

示例15: main

# 需要导入模块: from matplotlib.collections import LineCollection [as 别名]
# 或者: from matplotlib.collections.LineCollection import set_array [as 别名]
	def main(self):
		x_field = self.fields_by_key('x')[0]
		y_field = self.fields_by_key('y')[0]	
		x = np.array(self.slice_data(x_field,int))
		y = np.array(self.slice_data(y_field,int))
		n = len(x)
		render = StringIO.StringIO()
		
		###############################################################################
		# Fit IsotonicRegression and LinearRegression models

		ir = IsotonicRegression()

		y_ = ir.fit_transform(x, y)

		lr = LinearRegression()
		lr.fit(x[:, np.newaxis], y)  # x needs to be 2d for LinearRegression

		###############################################################################
		# plot result

		segments = [[[i, y[i]], [i, y_[i]]] for i in range(n)]
		lc = LineCollection(segments, zorder=0)
		lc.set_array(np.ones(len(y)))
		lc.set_linewidths(0.5 * np.ones(n))

		fig = plt.figure()
		plt.plot(x, y, 'r.', markersize=12)
		plt.plot(x, y_, 'g.-', markersize=12)
		plt.plot(x, lr.predict(x[:, np.newaxis]), 'b-')
		plt.gca().add_collection(lc)
		plt.legend(('Data', 'Isotonic Fit', 'Linear Fit'), loc='lower right')
		plt.title('Isotonic regression')
		plt.savefig(render,format='png')
		return render
开发者ID:quantbucket,项目名称:quantbucket-repo,代码行数:37,代码来源:isotonic_regression.py


注:本文中的matplotlib.collections.LineCollection.set_array方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。