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


Python collections.LineCollection类代码示例

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


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

示例1: hello

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,代码行数:35,代码来源:flaskapp.py

示例2: d3

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,代码行数:33,代码来源:flaskapp.py

示例3: plot_file_color

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,代码行数:26,代码来源:plotting.py

示例4: __init__

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,代码行数:32,代码来源:meshVisualize.py

示例5: gradient

    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,代码行数:25,代码来源:LCA.py

示例6: load_colorado_shapes

def load_colorado_shapes(m):

    # read all US counties
    rdr = shapefile.Reader("../USA_adm/USA_adm2")
    shapes = rdr.shapes()
    records = rdr.records()

    # only keep Colorado counties
    ndx = filter(lambda i: records[i][4] == 'Colorado', np.arange(len(shapes)))
    shapes = [shapes[i] for i in ndx]
    records = [records[i] for i in ndx]

    # modified from web tutorial
    # http://www.geophysique.be/2013/02/12/matplotlib-basemap-tutorial-10-shapefiles-unleached-continued/
    line_col = []
    for record, shape in zip(records, shapes):
        lons,lats = zip(*shape.points)
        data = np.array(m(lons, lats)).T
 
        if len(shape.parts) == 1:
            segs = [data,]
        else:
            segs = []
            for i in range(1,len(shape.parts)):
                index = shape.parts[i-1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
                segs.append(data[index2:])
 
        lines = LineCollection(segs, antialiaseds=(1,))
        lines.set_edgecolors('k')
        lines.set_linewidth(0.8)
        line_col.append(lines)

    return line_col
开发者ID:vejmelkam,项目名称:wrfx,代码行数:35,代码来源:postproc_wrfout.py

示例7: main

	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,代码行数:35,代码来源:isotonic_regression.py

示例8: show_mf_wave

def show_mf_wave(**kwargs):
    ion()
    mjfile='data/mf_W1%s_W2%s_U%s_N%s_dmu%s.npy'%(kwargs.get('K1'),kwargs.get('K2'),kwargs.get('U'),kwargs.get('nsite'),kwargs.get('dmu'))
    pls=load(mjfile)
    ampl=(pls[:2]*pls[:2].conj()).real
    print 'Magnituede %s'%sum(ampl,axis=1)
    if ONSV:
        return
    #mjfile2='data/mf_W1%s_W2%s_U%s_N%s_dmu%s.npy'%(kwargs.get('K1'),kwargs.get('K2'),kwargs.get('U'),kwargs.get('nsite'),-kwargs.get('dmu'))
    #pls2=load(mjfile2)
    #overlap=(pls2[:2].dot(pls[:2].T.conj()))
    #print overlap
    #subplot(211)

    #plot(abs(ket_even.state))
    #ylim(0,0.5)
    #subplot(212)
    #plot(abs(ket_odd.state))
    #ylim(0,0.5)
    #pdb.set_trace()
    lw=2
    lc='r'
    nsite=pls.shape[1]
    for n in xrange(2):
        pln=ampl[n]
        ax=subplot(121+n)
        lc=LineCollection([[(i,0),(i,pln[i].item())] for i in xrange(nsite)])
        lc.set_linewidth(lw)
        ax.add_collection(lc)

        ax.autoscale()
        ax.margins(0.1)
    pdb.set_trace()
开发者ID:GiggleLiu,项目名称:apps,代码行数:33,代码来源:views.py

示例9: plot_Kiel_diagram

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,代码行数:28,代码来源:fileio.py

示例10: __init__

class Tracks:
    def __init__(self, ax, stormcells):
        self.tracks = None
        self.update_trackmap(ax, stormcells)

    def update_trackmap(self, ax, stormcells):
        if self.tracks is not None:
            self.tracks.remove()
            self.tracks = None
        if self.tracks is None:
            self.tracks = LineCollection([])
            ax.add_collection(self.tracks)

        self.trackmap = []
        for trackid in range(np.max(stormcells['track_id']) + 1):
            indexes = np.where(stormcells['track_id'] == trackid)[0]
            # Makes sure the track segments are in chronological order
            indexes = indexes[np.argsort(stormcells['frame_index'][indexes])]
            self.trackmap.append(indexes)

    def update_frame(self, frame_index, stormcells):
        segments = []
        for trackid, indexes in enumerate(self.trackmap):
            trackdata = stormcells[indexes]
            trackdata = trackdata[trackdata['frame_index'] <= frame_index]
            segments.append(zip(trackdata['xcent'], trackdata['ycent'])
                            or [(np.nan, np.nan)])
        self.tracks.set_segments(segments)
开发者ID:dboyliao,项目名称:Learn_Matplotlib,代码行数:28,代码来源:plain_tracks.py

示例11: plotflow

def plotflow(nm,j,ylabel='Congestion Window Size',state=False):
  i=0

  if state and not isinstance(nm,list):
    r = (1,0,0)
    g = (0,1,0)
    b = (0,0,1)
    clrs = np.zeros((flows[nm][3].shape[0],3))
    clrs[flows[nm][-1]=='SS']=g
    clrs[flows[nm][-1]=='CA']=b
    clrs[flows[nm][-1]=='FR']=r
    points = np.array([flows[nm][i], flows[nm][j]]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    lc = LineCollection(segments, colors=clrs)
    lc.set_linewidth(1.7)
    fig, ax = plt.subplots()
    ax.add_collection(lc)
    ax.autoscale_view()

    line_ss = mlines.Line2D([], [], color='green', label='Slow Start')
    line_ca = mlines.Line2D([], [], color='blue', label='Congestion Avoidance')
    line_fr = mlines.Line2D([], [], color='red', label='Fast Recovery')
    plt.legend(handles=[line_ss,line_ca,line_fr])
  else:
    if isinstance(nm,list):
      for n in nm:
        if n in flows:
          plt.plot(flows[n][i],flows[n][j],label=n)
    else:
      plt.plot(flows[nm][i],flows[nm][j])
    plt.legend()
  plt.xlabel('time (s)')
  plt.ylabel(ylabel)
  plt.show()
开发者ID:elifriedman,项目名称:PythonNetworkSimulator,代码行数:35,代码来源:visualize.py

示例12: traceShape

def traceShape(file_shapefile):
    r = shapefile.Reader(file_shapefile)
    shapes = r.shapes()
    records = r.records()
    #sc_fac = 100000
    for record, shape in zip(records,shapes):
        #print shape.points
        lonsh,latsh = zip(*shape.points)
        # lonsh = [x/sc_fac for x in lonsh]
        # latsh = [x/sc_fac for x in latsh]
        data = np.array(m(lonsh, latsh)).T
     
        if len(shape.parts) == 1:
            segs = [data,]
        else:
            segs = []
            for i in range(1,len(shape.parts)):
                index = shape.parts[i-1]
                index2 = shape.parts[i]
                segs.append(data[index:index2])
            segs.append(data[index2:])
     
        lines = LineCollection(segs,antialiaseds=(1,))
        # lines.set_facecolors(cm.jet(np.random.rand(1)))
        lines.set_edgecolors('k')
        lines.set_linewidth(0.1)
        ax.add_collection(lines)

    return None
开发者ID:dluzenst,项目名称:nostromo,代码行数:29,代码来源:mapfrance2.py

示例13: _draw_segments

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,代码行数:30,代码来源:misc.py

示例14: colorline

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,代码行数:33,代码来源:floris_plot_lib.py

示例15: update_line

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,代码行数:28,代码来源:plot_figures.py


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