我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.collections.LineCollection()。
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)
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()
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)
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()
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)
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)
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)
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)
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
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
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
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
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)
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)
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)
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)
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')
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
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()
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)
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)
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)
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)
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)
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
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
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', snap=True) # added snap=True #----------------------------------------------- # 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)
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 = [list(zip(X[i], Y[i])) for i in xrange(N)] else: xy = [list(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)
def plotTrajectory(data): # points = np.array([x, y]).T.reshape(-1, 1, 2) # segments = np.concatenate([points[:-1], points[1:]], axis=1) # # lc = LineCollection(segments, cmap=plt.get_cmap('Spectral')) # lc.set_array(z) # #lc.set_linewidth(2) # # plt.gca().add_collection(lc) import matplotlib.cm as cm cmap = cm.jet; c = np.linspace(0, 10, len(data[:,0])); plt.scatter(data[:,0], data[:,1], c = c, cmap = cmap, marker = '+');
def plot_colored_line(x,y, color, cmap = 'spectral_r', line_width = 2): """Plot a line with color code""" segments = np.array([x, y]).T.reshape(-1, 1, 2); segments = np.concatenate([segments[:-1], segments[1:]], axis=1); lc = LineCollection(segments, cmap=cmap); lc.set_array(np.array(color)); #lc.set_linewidth(line_width); plt.gca().add_collection(lc)
def _animate(fig, ax, frame_data, line_width=2, fps=10, tail_color='r', tail_alpha=0.75, head_color='b', head_alpha=1): segments, segment_frames, timestamps, fade_frames = frame_data head_color = np.array(to_rgb(head_color))[None] tail_color = np.array(to_rgb(tail_color))[None] # start with all segments transparent segment_colors = np.zeros((len(segments), 4), dtype=float) lines = LineCollection(segments, linewidths=line_width, colors=segment_colors) ax.add_collection(lines) timer = ax.text(1, 0, '0:00:00', transform=ax.transAxes, zorder=3, verticalalignment='bottom', horizontalalignment='right', bbox=dict(facecolor='white')) def update_frame(frame_idx): frame_diff = frame_idx - segment_frames mask = frame_diff < 0 # compute head alpha alpha1 = 1 - np.minimum(frame_diff/fade_frames, 1) alpha1[mask] = 0 alpha1 *= head_alpha # compute tail alpha alpha2 = (1 - mask) * tail_alpha # composite alpha and colors color, alpha = _blend_alpha(head_color, alpha1, tail_color, alpha2) segment_colors[:, :3] = color segment_colors[:, 3] = alpha lines.set_color(segment_colors) timer.set_text(timestamps[frame_idx]) return lines, timer interval = 1000. / fps return FuncAnimation(fig, update_frame, frames=len(timestamps), blit=True, interval=interval, repeat=True)
def plot_edges(pts, edges, title=None, clabel=None, save=None, show=True): nppts = np.array(pts) npedges = np.array(edges) lc = LineCollection(nppts[npedges]) fig = Figure(title=title, clabel=clabel, save=save, show=show) fig.ax.add_collection(lc) plt.xlim(nppts[:, 0].min(), nppts[:, 0].max()) plt.ylim(nppts[:, 1].min(), nppts[:, 1].max()) plt.plot(nppts[:, 0], nppts[:, 1], 'ro') return fig
def __init__(self, plotman): self.plotman = plotman self.axes = plotman.axes self.mode_colors = plotman.mode_colors # create a blank invariant violation polys self.inv_vio_polys = collections.PolyCollection([], animated=True, alpha=0.7, edgecolor='red', facecolor='red') self.axes.add_collection(self.inv_vio_polys) # create a blank currently-tracked set of states poly self.cur_state_line2d = Line2D([], [], animated=True, color='k', lw=2, mew=2, ms=5, fillstyle='none') self.axes.add_line(self.cur_state_line2d) self.parent_to_polys = OrderedDict() self.parent_to_markers = OrderedDict() self.waiting_list_mode_to_polys = OrderedDict() self.aggregation_mode_to_polys = OrderedDict() self.trace = collections.LineCollection( [[(0, 0)]], animated=True, colors=('k'), linewidths=(3), linestyle='dashed') self.axes.add_collection(self.trace) if plotman.settings.extra_lines is not None: lines = plotman.settings.extra_lines self.extra_lines_col = collections.LineCollection( lines, animated=True, colors=('gray'), linewidths=(2), linestyle='dashed') self.axes.add_collection(self.extra_lines_col) else: self.extra_lines_col = None self.freeze_attrs()
def plotGraph(self, pltax, offset0 = [600, -800], offset1 = [600, 800]): self.regghalf[0].plotGraph(pltax, offset0) self.regghalf[1].plotGraph(pltax, offset1) # # add offset for nid in self.gnodesplotpos.keys(): if nid.startswith('assrgt'): self.gnodesplotpos[nid] = map(add, self.gnodesplotpos[nid], [offset0[0], 0]) if nid.startswith('asslft'): self.gnodesplotpos[nid] = map(add, self.gnodesplotpos[nid], [offset1[0], 0]) # make composed gnodesplotpos self.composedgnodesplotpos = {} for key in self.gnodesplotpos.keys(): self.composedgnodesplotpos[key] = self.gnodesplotpos[key] for key in self.regghalf[0].gnodesplotpos.keys(): self.composedgnodesplotpos[key] = self.regghalf[0].gnodesplotpos[key] for key in self.regghalf[0].graphtpp.gnodesplotpos.keys(): self.composedgnodesplotpos[key] = self.regghalf[0].graphtpp.gnodesplotpos[key] for key in self.regghalf[1].gnodesplotpos.keys(): self.composedgnodesplotpos[key] = self.regghalf[1].gnodesplotpos[key] for key in self.regghalf[1].graphtpp.gnodesplotpos.keys(): self.composedgnodesplotpos[key] = self.regghalf[1].graphtpp.gnodesplotpos[key] transitedges = [] transferedges = [] for nid0, nid1, reggedgedata in self.regg.edges(data=True): if reggedgedata['edgetype'] is 'asstransit': transitedges.append([self.composedgnodesplotpos[nid0][:2], self.composedgnodesplotpos[nid1][:2]]) if reggedgedata['edgetype'] is 'asstransfer': transferedges.append([self.composedgnodesplotpos[nid0][:2], self.composedgnodesplotpos[nid1][:2]]) transitec = mc.LineCollection(transitedges, colors=[1,0,1,1], linewidths=1) transferec = mc.LineCollection(transferedges, colors=[.5,.5,0,.03], linewidths=1) pltax.add_collection(transferec) pltax.add_collection(transitec)
def displayGraph2( nbPillar,g,r, lw): x1 = [] x2 = [] y1 = [] y2 = [] lines = [] c = [] d2 = copy.deepcopy(g) while len(d2) > 0: n1 = d2.keys()[0] n2 = d2[n1].keys()[0] c1 = pillar2tocart(n1,nbPillar,r) c2 = pillar2tocart(n2,nbPillar,r) #x1.append(c1[0]) #x2.append(c2[0]) #y1.append(c1[1]) #y2.append(c2[1]) lines.append(((c1[0],-c1[1]),(c2[0],-c2[1]))) c.append( (0,0,0,1) ) decreaseWeightEdge(d2,n1,n2) #lines = plt.plot( np.stack(x1),np.stack(y1),np.stack(x2),np.stack(y2)) #plt.setp(lines, color='white', linewidth=1.0) #plt.gca().set_axis_bgcolor('black') lc = mc.LineCollection(lines,colors=np.array(c) ,linewidths=lw) fig, ax = pl.subplots() ax.add_collection(lc) ax.autoscale() ax.margins(0.1) fig.show() #plt.show()
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`. .. versionadded:: 0.6.0 Parameters ---------- ax : :class:`matplotlib:matplotlib.axes.Axes` lines : nested :class:`numpy:numpy.ndarray` 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)
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 # Read in the merged data file
def plot(self, ax=None, cmapname=None, cmap=None, linewidth=1, edgecolor='grey', facecolor=None, alpha=1): """Plot the geometries on the basemap using the defined colors Parameters: ----------- ax : matplotlib.axis object An axis object for plots. Overwrites the self.ax attribute. cmapname : string Name of the color map from matplotlib (LINK!) (default: 'seismic') cmap : matplotlib colormap You can create you own colormap and pass it to the plot. linewidth : float Width of the lines. edgecolor : string, float or iterable Definition of the edge color. Can be an iterable with a color definition for each geometry, a string with one color for all geometries or a float to define one color for all geometries from the cmap. facecolor : string, float or iterable Definition of the face color. See edgecolor. alpha : float Level of transparency. """ if ax is not None: self.ax = ax n = 0 if facecolor is None: facecolor = self.color if edgecolor is None: edgecolor = self.color if cmapname is not None: self.cmapname = cmapname if self.data is not None: self.data = np.array(self.data) if cmap is None: cmap = plt.get_cmap(self.cmapname) for geo in self.geometries: vectors = self.get_vectors_from_postgis_map(geo) lines = LineCollection(vectors, antialiaseds=(1, )) lines.set_facecolors(self.select_color(facecolor, cmap, n)) lines.set_edgecolors(self.select_color(edgecolor, cmap, n)) lines.set_linewidth(linewidth) lines.set_alpha(alpha) self.ax.add_collection(lines) n += 1
def cie_1931_wavelength_annotations(wavelengths, fig=None, ax=None): ''' Draws lines normal to the spectral locust on a CIE 1931 diagram and writes the text for each wavelength. Args: wavelengths (`iterable`): set of wavelengths to annotate. fig (`matplotlib.figure.Figure`): figure to draw on. ax (`matplotlib.axes.Axis`): axis to draw in. Returns: `tuple` containing: `matplotlib.figure.Figure`: figure containing the annotations. `matplotlib.axes.Axis`: axis containing the annotations. Notes: see SE: https://stackoverflow.com/questions/26768934/annotation-along-a-curve-in-matplotlib ''' # some tick parameters tick_length = 0.025 text_offset = 0.06 # convert wavelength to u' v' coordinates wavelengths = np.asarray(wavelengths) idx = np.arange(1, len(wavelengths) - 1, dtype=int) wvl_lbl = wavelengths[idx] xy = XYZ_to_xy(wavelength_to_XYZ(wavelengths)) x, y = xy[..., 0][idx], xy[..., 1][idx] x_last, y_last = xy[..., 0][idx - 1], xy[..., 1][idx - 1] x_next, y_next = xy[..., 0][idx + 1], xy[..., 1][idx + 1] angle = atan2(y_next - y_last, x_next - x_last) + pi / 2 cos_ang, sin_ang = cos(angle), sin(angle) x1, y1 = x + tick_length * cos_ang, y + tick_length * sin_ang x2, y2 = x + text_offset * cos_ang, y + text_offset * sin_ang fig, ax = share_fig_ax(fig, ax) tick_lines = LineCollection(np.c_[x, y, x1, y1].reshape(-1, 2, 2), color='0.25', lw=1.25) ax.add_collection(tick_lines) for i in range(len(idx)): ax.text(x2[i], y2[i], str(wvl_lbl[i]), va="center", ha="center", clip_on=True) return fig, ax
def cie_1976_wavelength_annotations(wavelengths, fig=None, ax=None): ''' Draws lines normal to the spectral locust on a CIE 1976 diagram and writes the text for each wavelength. Args: wavelengths (`iterable`): set of wavelengths to annotate. fig (`matplotlib.figure.Figure`): figure to draw on. ax (`matplotlib.axes.Axis`): axis to draw in. Returns: `tuple` containing: `matplotlib.figure.Figure`: figure containing the annotations. `matplotlib.axes.Axis`: axis containing the annotations. Notes: see SE: https://stackoverflow.com/questions/26768934/annotation-along-a-curve-in-matplotlib ''' # some tick parameters tick_length = 0.025 text_offset = 0.06 # convert wavelength to u' v' coordinates wavelengths = np.asarray(wavelengths) idx = np.arange(1, len(wavelengths) - 1, dtype=int) wvl_lbl = wavelengths[idx] uv = XYZ_to_uvprime(wavelength_to_XYZ(wavelengths)) u, v = uv[..., 0][idx], uv[..., 1][idx] u_last, v_last = uv[..., 0][idx - 1], uv[..., 1][idx - 1] u_next, v_next = uv[..., 0][idx + 1], uv[..., 1][idx + 1] angle = atan2(v_next - v_last, u_next - u_last) + pi / 2 cos_ang, sin_ang = cos(angle), sin(angle) u1, v1 = u + tick_length * cos_ang, v + tick_length * sin_ang u2, v2 = u + text_offset * cos_ang, v + text_offset * sin_ang fig, ax = share_fig_ax(fig, ax) tick_lines = LineCollection(np.c_[u, v, u1, v1].reshape(-1, 2, 2), color='0.25', lw=1.25) ax.add_collection(tick_lines) for i in range(len(idx)): ax.text(u2[i], v2[i], str(wvl_lbl[i]), va="center", ha="center", clip_on=True) return fig, ax
def draw_group(data, panel_params, coord, ax, **params): data = coord.transform(data, panel_params) data['size'] *= SIZE_FACTOR has_x = 'x' in data.columns has_y = 'y' in data.columns if has_x or has_y: n = len(data) else: return rugs = [] sides = params['sides'] xmin, xmax = panel_params['x_range'] ymin, ymax = panel_params['y_range'] xheight = (xmax-xmin)*0.03 yheight = (ymax-ymin)*0.03 if has_x: if 'b' in sides: x = np.repeat(data['x'].values, 2) y = np.tile([ymin, ymin+yheight], n) rugs.extend(make_line_segments(x, y, ispath=False)) if 't' in sides: x = np.repeat(data['x'].values, 2) y = np.tile([ymax-yheight, ymax], n) rugs.extend(make_line_segments(x, y, ispath=False)) if has_y: if 'l' in sides: x = np.tile([xmin, xmin+xheight], n) y = np.repeat(data['y'].values, 2) rugs.extend(make_line_segments(x, y, ispath=False)) if 'r' in sides: x = np.tile([xmax-xheight, xmax], n) y = np.repeat(data['y'].values, 2) rugs.extend(make_line_segments(x, y, ispath=False)) color = to_rgba(data['color'], data['alpha']) coll = mcoll.LineCollection(rugs, edgecolor=color, linewidth=data['size'], linestyle=data['linetype'], zorder=params['zorder']) ax.add_collection(coll)
def _colorline(ax, x, y, color = (0, 0, 0), **kwargs): ''' Plots the curve `y(x)` with linearly increasing alpha. Adapted from `http://nbviewer.jupyter.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb`_. ''' # A bit hacky... But there doesn't seem to be # an easy way to get the hex code for a named color... if isinstance(color, string_types): if color.startswith("#"): hex = color[1:] else: if len(color) == 1: if color == 'k': color = 'black' elif color == 'r': color = 'red' elif color == 'b': color = 'blue' elif color == 'g': color = 'green' elif color == 'y': color = 'yellow' elif color == 'w': color = 'white' else: # ?! color = 'black' hex = matplotlib.colors.cnames[color.lower()][1:] r, g, b = tuple(int(hex[i:i+2], 16) / 255. for i in (0, 2, 4)) else: r, g, b = color colors = [(r, g, b, i) for i in np.linspace(0, 1, 3)] cmap = LinearSegmentedColormap.from_list('alphacmap', colors, N = 1000) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, array = np.linspace(0.0, 1.0, len(x)), cmap = cmap, norm = pl.Normalize(0.0, 1.0), **kwargs) ax.add_collection(lc) return lc