def draw_networkx_nodes(G, pos, nodelist=None, node_size=300, node_color='r', node_shape='o', alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, **kwds): """Draw nodes of graph G This draws only the nodes of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx.layout for functions that compute node positions. nodelist is an optional list of nodes in G to be drawn. If provided only the nodes in nodelist will be drawn. see draw_networkx for the list of other optional parameters. """ from matplotlib.pylab import gca, hold, draw_if_interactive if ax is None: ax = gca() if nodelist is None: nodelist = G.nodes() x = asarray([pos[v][0] for v in nodelist]) y = asarray([pos[v][1] for v in nodelist]) node_collection = ax.scatter(x, y, s=node_size, c=node_color, marker=node_shape, cmap=cmap, vmin=vmin, vmax=vmax, alpha=alpha) node_collection.set_zorder(2) return node_collection
def draw_markers(self, gc, path, rgbFace, x, y, trans): self.check_gc(gc, rgbFace) fillp = rgbFace is not None marker = self.file.markerObject(path, fillp, self.gc._linewidth) x, y = trans.numerix_x_y(asarray(x), asarray(y)) x, y = self.dpi_factor * x, self.dpi_factor * y nan_at = isnan(x) | isnan(y) self.file.output(Op.gsave) ox, oy = 0, 0 for i in range(len(x)): if nan_at[i]: continue dx, dy, ox, oy = x[i] - ox, y[i] - oy, x[i], y[i] self.file.output(1, 0, 0, 1, dx, dy, Op.concat_matrix, marker, Op.use_xobject) self.file.output(Op.grestore)
def set_dashes(self, offset, dashes): self._dashes = offset, dashes if dashes == None: self.ctx.set_dash([], 0) # switch dashes off else: self.ctx.set_dash(self.renderer.points_to_pixels(asarray(dashes)), offset)
def points_to_pixels(self, points): """ convert point measures to pixes using dpi and the pixels per inch of the display """ return asarray(points) * (PIXELS_PER_INCH / 72.0 * self.dpi.get() / 72.0)
def set_dashes(self, offset, dashes): self._dashes = offset, dashes if dashes == None: self.ctx.set_dash([], 0) # switch dashes off else: dashes_pixels = self.renderer.points_to_pixels(asarray(dashes)) self.ctx.set_dash(dashes_pixels, offset)
def to_rgba(self, x, alpha=1.0): # assume normalized rgb, rgba x = asarray(x) if len(x.shape) > 2: return x x = self.norm(x) return self.cmap(x, alpha)
def __call__(self, value): vmin = self.vmin vmax = self.vmax if type(value) in [IntType, FloatType]: vtype = 'scalar' val = array([value]) else: vtype = 'array' val = nx.asarray(value) # if both vmin is None and vmax is None, we'll automatically # norm the data to vmin/vmax of the actual data, so the # clipping step won't be needed. if vmin is None and vmax is None: needs_clipping = False else: needs_clipping = True if vmin is None or vmax is None: rval = nx.ravel(val) #do this if sentinels (values to ignore in data) if self.ignore: sortValues = nx.sort(rval) if vmin is None: # find the lowest non-sentinel value for thisVal in sortValues: if thisVal not in self.ignore: vmin = thisVal #vmin is the lowest non-sentinel value break else: vmin = 0. if vmax is None: for thisVal in sortValues[::-1]: if thisVal not in self.ignore: vmax = thisVal #vmax is the greatest non-sentinel value break else: vmax = 0. else: if vmin is None: vmin = min(rval) if vmax is None: vmax = max(rval) if vmin > vmax: raise ValueError("minvalue must be less than or equal to maxvalue") elif vmin == vmax: return 0. * value else: if needs_clipping: val = nx.clip(val, vmin, vmax) result = (1.0 / (vmax - vmin)) * (val - vmin) # replace sentinels with original (non-normalized) values for thisIgnore in self.ignore: result = nx.where(val == thisIgnore, thisIgnore, result) if vtype == 'scalar': result = result[0] return result
def __call__(self, value): vmin = self.vmin vmax = self.vmax if type(value) in [IntType, FloatType]: vtype = 'scalar' val = array([value]) else: vtype = 'array' val = nx.asarray(value) # if both vmin is None and vmax is None, we'll automatically # norm the data to vmin/vmax of the actual data, so the # clipping step won't be needed. if vmin is None and vmax is None: needs_clipping = False else: needs_clipping = True if vmin is None or vmax is None: rval = nx.ravel(val) #do this if sentinels (values to ignore in data) if self.ignore: sortValues=nx.sort(rval) if vmin is None: # find the lowest non-sentinel value for thisVal in sortValues: if thisVal not in self.ignore: vmin=thisVal #vmin is the lowest non-sentinel value break else: vmin=0. if vmax is None: for thisVal in sortValues[::-1]: if thisVal not in self.ignore: vmax=thisVal #vmax is the greatest non-sentinel value break else: vmax=0. else: if vmin is None: vmin = min(rval) if vmax is None: vmax = max(rval) if vmin > vmax: raise ValueError("minvalue must be less than or equal to maxvalue") elif vmin==vmax: return 0.*value else: if needs_clipping: val = nx.clip(val,vmin, vmax) result = (1.0/(vmax-vmin))*(val-vmin) # replace sentinels with original (non-normalized) values for thisIgnore in self.ignore: result = nx.where(val==thisIgnore,thisIgnore,result) if vtype == 'scalar': result = result[0] return result
def draw_markers(self, gc, path, rgbFace, x, y, trans): self.check_gc(gc, rgbFace) fillp = rgbFace is not None marker = self.file.markerObject(path, fillp, self.gc._linewidth) x, y = trans.numerix_x_y(asarray(x), asarray(y)) x, y = self.dpi_factor * x, self.dpi_factor * y nan_at = isnan(x) | isnan(y) self.file.output(Op.gsave) ox, oy = 0, 0 for i in range(len(x)): if nan_at[i]: continue dx, dy, ox, oy = x[i]-ox, y[i]-oy, x[i], y[i] self.file.output(1, 0, 0, 1, dx, dy, Op.concat_matrix, marker, Op.use_xobject) self.file.output(Op.grestore)
def to_rgba(self, x, alpha=1.0): # assume normalized rgb, rgba #print '0', type(x), x.shape x = asarray(x) #print '1', type(x), x.shape if len(x.shape)>2: return x x = self.norm(x) x = self.cmap(x, alpha) return x
def to_rgba(self, x, alpha=1.0): # assume normalized rgb, rgba #print '0', type(x), x.shape x = asarray(x) #print '1', type(x), x.shape if len(x.shape) > 2: return x x = self.norm(x) x = self.cmap(x, alpha) return x
def set_dashes(self, dash_offset, dash_list): GraphicsContextBase.set_dashes(self, dash_offset, dash_list) if dash_list == None: self.gdkGC.line_style = gdk.LINE_SOLID else: pixels = self.renderer.points_to_pixels(asarray(dash_list)) dl = [max(1, int(round(val))) for val in pixels] self.gdkGC.set_dashes(dash_offset, dl) self.gdkGC.line_style = gdk.LINE_ON_OFF_DASH
def dash_path(self, gc, path): """ Add dashes to the path and return it if dashes are set """ offset, dashes = gc.get_dashes() if dashes is not None: dashes = tuple(self.points_to_pixels(asarray(dashes))) return path.dash(offset, dashes) else: return path
def get_colours(n): """ Return n pastel colours. """ base = asarray([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) if n <= 3: return base[0:n] # how many new colours to we need to insert between # red and green and between green and blue? needed = (((n - 3) + 1) / 2, (n - 3) / 2) colours = [] for start in (0, 1): for x in linspace(0, 1, needed[start] + 2): colours.append((base[start] * (1.0 - x)) + (base[start + 1] * x)) return [pastel(c) for c in colours[0:n]]
def get_colours(n): """ Return n pastel colours. """ base = asarray([[1,0,0], [0,1,0], [0,0,1]]) if n <= 3: return base[0:n] # how many new colours to we need to insert between # red and green and between green and blue? needed = (((n - 3) + 1) / 2, (n - 3) / 2) colours = [] for start in (0, 1): for x in linspace(0, 1, needed[start]+2): colours.append((base[start] * (1.0 - x)) + (base[start+1] * x)) return [pastel(c) for c in colours[0:n]]
def draw_networkx_nodes(G, pos, nodelist=None, node_size=300, node_color='r', node_shape='o', alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, linewidths=None, **kwds): """Draw nodes of graph G This draws only the nodes of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx.layout for functions that compute node positions. nodelist is an optional list of nodes in G to be drawn. If provided only the nodes in nodelist will be drawn. see draw_networkx for the list of other optional parameters. """ if ax is None: ax = matplotlib.pylab.gca() if nodelist is None: nodelist = G.nodes() if not nodelist or len(nodelist) == 0: # empty nodelist, no drawing return None try: xy = asarray([pos[v] for v in nodelist]) except KeyError, e: raise networkx.NetworkXError('Node %s has no position.' % e)
def draw_networkx_nodes(G, pos, nodelist=None, node_size=300, node_color='r', node_shape='o', alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, linewidths=None, **kwds): """Draw nodes of graph G This draws only the nodes of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx_v099.layout for functions that compute node positions. nodelist is an optional list of nodes in G to be drawn. If provided only the nodes in nodelist will be drawn. see draw_networkx_v099 for the list of other optional parameters. """ if ax is None: ax=matplotlib.pylab.gca() if nodelist is None: nodelist=G.nodes() if not nodelist or len(nodelist)==0: # empty nodelist, no drawing return None try: xy=asarray([pos[v] for v in nodelist]) except KeyError,e: raise networkx_v099.NetworkXError('Node %s has no position.'%e)
def pastel(colour, weight=2.4): """ Convert colour into a nice pastel shade""" rgb = asarray(colorConverter.to_rgb(colour)) # scale colour maxc = max(rgb) if maxc < 1.0 and maxc > 0: # scale colour scale = 1.0 / maxc rgb = rgb * scale # now decrease saturation total = asum(rgb) slack = 0 for x in rgb: slack += 1.0 - x # want to increase weight from total to weight # pick x s.t. slack * x == weight - total # x = (weight - total) / slack x = (weight - total) / slack rgb = [c + (x * (1.0 - c)) for c in rgb] return rgb
def pastel(colour, weight=2.4): """ Convert colour into a nice pastel shade""" rgb = asarray(colorConverter.to_rgb(colour)) # scale colour maxc = max(rgb) if maxc < 1.0 and maxc > 0: # scale colour scale = 1.0 / maxc rgb = rgb * scale # now decrease saturation total = sum(rgb) slack = 0 for x in rgb: slack += 1.0 - x # want to increase weight from total to weight # pick x s.t. slack * x == weight - total # x = (weight - total) / slack x = (weight - total) / slack rgb = [c + (x * (1.0-c)) for c in rgb] return rgb
def points_to_pixels(self, points): """ convert point measures to pixes using dpi and the pixels per inch of the display """ return asarray(points)*(PIXELS_PER_INCH/72.0*self.dpi.get()/72.0)
def closeto(x,y): return abs(asarray(x)-asarray(y))<1e-10
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, ax=None, **kwds): """Draw the edges of the graph G This draws only the edges of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx.layout for functions that compute node positions. edgelist is an optional list of the edges in G to be drawn. If provided, only the edges in edgelist will be drawn. See draw_networkx for the list of other optional parameters. """ from matplotlib.pylab import gca, hold, draw_if_interactive if ax is None: ax = gca() if edgelist is None: edgelist = G.edges() if not edgelist: # no edges! return None # set edge positions head = [] tail = [] for e in edgelist: # edge e can be a 2-tuple (Graph) or a 3-tuple (Xgraph) u = e[0] v = e[1] head.append(pos[u]) tail.append(pos[v]) edge_pos = asarray(zip(head, tail)) if not cb.iterable(width): lw = (width, ) else: lw = width # edge colors specified with floats won't work here # since LineCollection doesn't use ScalarMappable. # You can use an array of RGBA or text labels if not cb.is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color)==len(edge_pos): edge_colors = None else: edge_colors = (colorConverter.to_rgba(edge_color, alpha), ) if G.is_directed(): edge_collection = LineCollection( edge_pos, colors=edge_colors, linewidths=lw, antialiaseds=(1, ), linestyle=style, transOffset=ax.transData, ) edge_collection.set_alpha(alpha) else: arrows = [] for src, dst in edge_pos: x1, y1 = src x2, y2 = dst dx = x2 - x1 # x offset dy = y2 - y1 # y offset arrows.append(Arrow(x1, y1, dx, dy, width=lw).get_verts()) edge_collection = PolyCollection( arrows, facecolors=edge_colors, antialiaseds=(1, ), transOffset=ax.transData, ) # update view xx = [x for (x, y) in head + tail] yy = [y for (x, y) in head + tail] minx = amin(xx) maxx = amax(xx) miny = amin(yy) maxy = amax(yy) w = maxx - minx h = maxy - miny padx, pady = 0.05 * w, 0.05 * h corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady) ax.update_datalim(corners) ax.autoscale_view() edge_collection.set_zorder(1) # edges go behind nodes ax.add_collection(edge_collection) return edge_collection
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, node_size=300, # Added by qrancik **kwds): """Draw the edges of the graph G This draws only the edges of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx.layout for functions that compute node positions. edgelist is an optional list of the edges in G to be drawn. If provided, only the edges in edgelist will be drawn. edgecolor can be a list of matplotlib color letters such as 'k' or 'b' that lists the color of each edge; the list must be ordered in the same way as the edge list. Alternatively, this list can contain numbers and those number are mapped to a color scale using the color map edge_cmap. For directed graphs, "arrows" (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. See draw_networkx for the list of other optional parameters. """ if ax is None: ax=matplotlib.pylab.gca() if edgelist is None: edgelist=G.edges() if not edgelist or len(edgelist)==0: # no edges! return None # set edge positions edge_pos=asarray([(pos[e[0]],pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width,) else: lw = width if not cb.is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color)==len(edge_pos): if matplotlib.numerix.alltrue([cb.is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple([colorConverter.to_rgba(c,alpha) for c in edge_color]) elif matplotlib.numerix.alltrue([not cb.is_string_like(c) for c in edge_color]): # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must consist of either color names or numbers') else: if len(edge_color)==1: edge_colors = ( colorConverter.to_rgba(edge_color, alpha), ) else: raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges') # edge_collection = LineCollection(edge_pos, # Deleted by qrancik edge_collection = ArrowedLineCollection(edge_pos, # Added by qrancik colors = edge_colors, linewidths = lw, antialiaseds = (1,), linestyle = style, transOffset = ax.transData, ) edge_collection.set_alpha(alpha) # Added by Satyam arrow_collection=None if G.is_directed() and arrows: edge_collection.add_arrows(math.sqrt(node_size)/1.5) # Found emprically to work well. Maybe more systematic approach needed? arrow_colors = ( colorConverter.to_rgba('k', alpha), ) arrow_collection = LineCollection(edge_pos, # Added by qrancik colors = arrow_colors, linewidths = lw, antialiaseds = (1,), linestyle = style, transOffset = ax.transData, ) # need 0.87.7 or greater for edge colormaps mpl_version=matplotlib.__version__ if mpl_version.endswith('svn'): mpl_version=matplotlib.__version__[0:-3] if mpl_version.endswith('pre'): mpl_version=matplotlib.__version__[0:-3] if map(int,mpl_version.split('.'))>=[0,87,7]: if edge_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) edge_collection.set_array(asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() matplotlib.pylab.sci(edge_collection) # update view minx = amin(ravel(edge_pos[:,:,0])) maxx = amax(ravel(edge_pos[:,:,0])) miny = amin(ravel(edge_pos[:,:,1])) maxy = amax(ravel(edge_pos[:,:,1])) w = maxx-minx h = maxy-miny padx, pady = 0.05*w, 0.05*h corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady) ax.update_datalim( corners) ax.autoscale_view() edge_collection.set_zorder(1) # edges go behind nodes ax.add_collection(edge_collection) if arrow_collection: arrow_collection.set_zorder(1) # edges go behind nodes ax.add_collection(arrow_collection) return edge_collection
def __array__(self, t=None, context=None): if t is not None: return nx.asarray(self.value).astype(t) else: return nx.asarray(self.value, 'O')
def __array__(self, t = None, context = None): if t is not None: return nx.asarray(self.value).astype(t) else: return nx.asarray(self.value, 'O')
def closeto(x, y): return abs(asarray(x) - asarray(y)) < 1e-10
def to_rgba(self, x, alpha=1.0): # assume normalized rgb, rgba x = asarray(x) if len(x.shape)>2: return x x = self.norm(x) return self.cmap(x, alpha)
def autocorr(x, lag=1): """Returns the autocorrelation x.""" x = nx.asarray(x) mu = nx.mlab.mean(x) sigma = nx.mlab.std(x) return nx.dot(x[:-lag]-mu, x[lag:]-mu)/(sigma**2.)/(len(x) - lag)
def draw_networkx_edges(G, pos, edgelist=None, width=1.0, edge_color='k', style='solid', alpha=1.0, edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None, arrows=True, **kwds): """Draw the edges of the graph G This draws only the edges of the graph G. pos is a dictionary keyed by vertex with a two-tuple of x-y positions as the value. See networkx_v099.layout for functions that compute node positions. edgelist is an optional list of the edges in G to be drawn. If provided, only the edges in edgelist will be drawn. edgecolor can be a list of matplotlib color letters such as 'k' or 'b' that lists the color of each edge; the list must be ordered in the same way as the edge list. Alternatively, this list can contain numbers and those number are mapped to a color scale using the color map edge_cmap. For directed graphs, "arrows" (actually just thicker stubs) are drawn at the head end. Arrows can be turned off with keyword arrows=False. See draw_networkx_v099 for the list of other optional parameters. """ if ax is None: ax=matplotlib.pylab.gca() if edgelist is None: edgelist=G.edges() if not edgelist or len(edgelist)==0: # no edges! return None # set edge positions edge_pos=asarray([(pos[e[0]],pos[e[1]]) for e in edgelist]) if not cb.iterable(width): lw = (width,) else: lw = width if not cb.is_string_like(edge_color) \ and cb.iterable(edge_color) \ and len(edge_color)==len(edge_pos): if matplotlib.numerix.alltrue([cb.is_string_like(c) for c in edge_color]): # (should check ALL elements) # list of color letters such as ['k','r','k',...] edge_colors = tuple([colorConverter.to_rgba(c,alpha) for c in edge_color]) elif matplotlib.numerix.alltrue([not cb.is_string_like(c) for c in edge_color]): # numbers (which are going to be mapped with a colormap) edge_colors = None else: raise ValueError('edge_color must consist of either color names or numbers') else: if len(edge_color)==1: edge_colors = ( colorConverter.to_rgba(edge_color, alpha), ) else: raise ValueError('edge_color must be a single color or list of exactly m colors where m is the number or edges') edge_collection = LineCollection(edge_pos, colors = edge_colors, linewidths = lw, antialiaseds = (1,), linestyle = style, transOffset = ax.transData, ) edge_collection.set_alpha(alpha) # need 0.87.7 or greater for edge colormaps mpl_version=matplotlib.__version__ if mpl_version.endswith('svn'): mpl_version=matplotlib.__version__[0:-3] if mpl_version.endswith('pre'): mpl_version=matplotlib.__version__[0:-3] if map(int,mpl_version.split('.'))>=[0,87,7]: if edge_colors is None: if edge_cmap is not None: assert(isinstance(edge_cmap, Colormap)) edge_collection.set_array(asarray(edge_color)) edge_collection.set_cmap(edge_cmap) if edge_vmin is not None or edge_vmax is not None: edge_collection.set_clim(edge_vmin, edge_vmax) else: edge_collection.autoscale() matplotlib.pylab.sci(edge_collection) # else: # sys.stderr.write(\ # """matplotlib version >= 0.87.7 required for colormapped edges. # (version %s detected)."""%matplotlib.__version__) # raise UserWarning(\ # """matplotlib version >= 0.87.7 required for colormapped edges. # (version %s detected)."""%matplotlib.__version__) arrow_collection=None if G.directed and arrows: # a directed graph hack # draw thick line segments at head end of edge # waiting for someone else to implement arrows that will work arrow_colors = ( colorConverter.to_rgba('k', alpha), ) a_pos=[] p=1.0-0.25 # make head segment 25 percent of edge length for src,dst in edge_pos: x1,y1=src x2,y2=dst dx=x2-x1 # x offset dy=y2-y1 # y offset d=sqrt(float(dx**2+dy**2)) # length of edge if d==0: # source and target at same position continue if dx==0: # vertical edge xa=x2 ya=dy*p+y1 if dy==0: # horizontal edge ya=y2 xa=dx*p+x1 else: theta=arctan2(dy,dx) xa=p*d*cos(theta)+x1 ya=p*d*sin(theta)+y1 a_pos.append(((xa,ya),(x2,y2))) arrow_collection = LineCollection(a_pos, colors = arrow_colors, linewidths = [4*ww for ww in lw], antialiaseds = (1,), transOffset = ax.transData, ) # update view minx = amin(ravel(edge_pos[:,:,0])) maxx = amax(ravel(edge_pos[:,:,0])) miny = amin(ravel(edge_pos[:,:,1])) maxy = amax(ravel(edge_pos[:,:,1])) w = maxx-minx h = maxy-miny padx, pady = 0.05*w, 0.05*h corners = (minx-padx, miny-pady), (maxx+padx, maxy+pady) ax.update_datalim( corners) ax.autoscale_view() edge_collection.set_zorder(1) # edges go behind nodes ax.add_collection(edge_collection) if arrow_collection: arrow_collection.set_zorder(1) # edges go behind nodes ax.add_collection(arrow_collection) return edge_collection