def draw_spectral(G, **kwargs): """Draw the graph G with a spectral layout. Parameters ---------- G : graph A networkx graph kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the pos parameter which is not used by this function. """ draw(G, spectral_layout(G), **kwargs)
def draw_spectral(G, **kwargs): """Draw the graph G with a spectral layout. Parameters ---------- G : graph A networkx graph **kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the pos parameter which is not used by this function. """ draw(G, spectral_layout(G), **kwargs)
def draw_spectral(G, **kwargs): """Draw the graph G with a spectral 2D layout. Using the unnormalized Laplacion, the layout shows possible clusters of nodes which are an approximation of the ratio cut. The positions are the entries of the second and third eigenvectors corresponding to the ascending eigenvalues starting from the second one. Parameters ---------- G : graph A networkx graph kwargs : optional keywords See networkx.draw_networkx() for a description of optional keywords, with the exception of the pos parameter which is not used by this function. """ draw(G, spectral_layout(G), **kwargs)
def draw_spectral(G, **kwargs): """Draw the graph G with a spectral layout.""" draw(G,spectral_layout(G),**kwargs)
def draw_spectral(G, **kwargs): """Draw the graph G with a spectral layout.""" draw(G, spectral_layout(G), **kwargs)
def draw_spectral(G, **kwargs): """Draw the graph G with a spectral layout.""" from networkx.drawing.layout import spectral_layout draw(G, spectral_layout(G), **kwargs)
def draw_spectral(G, **kwargs): """Draw the graph G with a spectral layout.""" from networkx.drawing.layout import spectral_layout draw(G,spectral_layout(G),**kwargs)
def catcorr(df, layout='spring', mode='mpl', titleStr='', testSig=0.05, sRange=(50, np.inf), wRange=(0.5, np.inf), labelThresh=0.05, fontsize=14): """Make a network plot showing the correlations among the categorical variables in the columns of df. Each node is a unique value in one of the columns (Node is specified as a tuple (column, value)) Node size is proportional to the value's frequency. Each edge is a unique pair of values in two columns. Edge width is proportional to the frequency of the pairing. Parameters ---------- df : pandas.DataFrame Nodes will be created for each unique value within each column of this object layout : str Choose one of [twopi, fdp, circo, neato, dot] to change the layout of the nodes. See Graphviz for details about each layout. mode : str Specifies whether the resulting plot will be a matplotlib figure (default: 'mpl') OR if any other value it specifies the filename of a figure to be posted to plot.ly (user needs to be logged in previously). titleStr : str Printed at the top of the plot. testSig : float If non-zero then testSig is used as the significance cutoff for plotting a highlighted edge. For each edge, tests the statistical hypothesis that number of observed pairings between values in two columns is significantly different than what one would expect based on their marginal frequencies. Note: there is FDR-adjustment for multiple comparisons. sRange,wRange : tuples of length 2 Contains the min and max node sizes or edge widths in points, for scaling Examples -------- >>> import plotly.plotly as py >>> py.sign_in([username], [api_key]) >>> df = generate_test_data() >>> catcorr(df, layout = 'neato', mode = 'catcorr_example') [Posts a catcorr plot to plot.ly] """ """Compute odds-ratios, p-values and FDR-adjusted q-values for each edge""" g = compute_graph(df) """Compute attributes of edges and nodes""" edgewidth = np.array([d['weight'] for n1, n2, d in g.edges(data=True)]) nodesize = np.array([d['freq'] for n, d in g.nodes(data=True)]) nColors = np.min([np.max([len(df.columns), 3]), 9]) colors = palettable.colorbrewer.get_map('Set1', 'Qualitative', nColors).mpl_colors cmap = {c:color for c, color in zip(df.columns, itertools.cycle(colors))} nodecolors = [cmap[n[0]] for n in g.nodes()] if layout == 'twopi': """If using this layout specify the most common node as the root""" freq = {n:d['freq'] for n, d in g.nodes(data=True)} pos = nx.graphviz_layout(g, prog=layout, root=np.max(list(freq.keys()), key=freq.get)) elif layout == 'spring': pos = spring_layout(g) elif layout == 'spectral': pos = spectral_layout(g) else: pos = nx.graphviz_layout(g, prog=layout) """Use either matplotlib or plot.ly to plot the network""" if mode == 'mpl': plt.clf() figh = plt.gcf() axh = figh.add_axes([0.04, 0.04, 0.92, 0.92]) axh.axis('off') figh.set_facecolor('white') #nx.draw_networkx_edges(g,pos,alpha=0.5,width=sznorm(edgewidth,mn=0.5,mx=10), edge_color='k') #nx.draw_networkx_nodes(g,pos,node_size=sznorm(nodesize,mn=500,mx=5000),node_color=nodecolors,alpha=1) ew = szscale(edgewidth, mn=wRange[0], mx=wRange[1]) for es, e in zip(ew, g.edges()): x1, y1=pos[e[0]] x2, y2=pos[e[1]] props = dict(color='black', alpha=0.4, zorder=1) if testSig and g[e[0]][e[1]]['qvalue'] < testSig: if g[e[0]][e[1]]['OR'] > 1.: props['color']='orange' else: props['color']='green' props['alpha']=0.8 plt.plot([x1, x2], [y1, y2], '-', lw=es, **props) plt.scatter(x=[pos[s][0] for s in g.nodes()], y=[pos[s][1] for s in g.nodes()], s=szscale(nodesize, mn=sRange[0], mx=sRange[1]), #Units for scatter is (size in points)**2 c=nodecolors, alpha=1, zorder=2) for n, d in g.nodes(data=True): if d['freq'] >= labelThresh: plt.annotate(n[1], xy=pos[n], fontname='Bitstream Vera Sans', size=fontsize, weight='bold', color='black', va='center', ha='center') colorLegend(labels=df.columns, colors=[c for x, c in zip(df.columns, colors)], loc=0, title='N = %1.0f' % (~df.isnull()).all(axis=1).sum(axis=0)) plt.title(titleStr) elif PLOTLY: """Send the plot to plot.ly""" data = [] for es, e in zip(szscale(edgewidth, mn=wRange[0], mx=wRange[1]), g.edges()): x1, y1=pos[e[0]] x2, y2=pos[e[1]] props = dict(color='black', opacity=0.4) if testSig and g[e[0]][e[1]]['qvalue'] < testSig: if g[e[0]][e[1]]['OR'] > 1.: props['color']='orange' else: props['color']='green' props['opacity']=0.8 tmp = pygo.Scatter(x=[x1, x2], y=[y1, y2], mode='lines', line=pygo.Line(width=es, **props), showlegend=False) data.append(tmp) """May need to add sqrt() to match mpl plots""" nodesize = szscale(nodesize, mn=sRange[0], mx=sRange[1]) #Units for plotly.Scatter is (size in points) for col in list(cmap.keys()): ind = [nodei for nodei, node in enumerate(g.nodes()) if node[0]==col] tmp = pygo.Scatter(x=[pos[s][0] for nodei, s in enumerate(g.nodes()) if nodei in ind], y=[pos[s][1] for nodei, s in enumerate(g.nodes()) if nodei in ind], mode='markers', name=col, text=[node[1] for nodei, node in enumerate(g.nodes()) if nodei in ind], textposition='middle center', marker=pygo.Marker(size=nodesize[ind], color=[color2str(nc) for nodei, nc in enumerate(nodecolors) if nodei in ind])) data.append(tmp) layout = pygo.Layout(title=titleStr, showlegend=True, xaxis=pygo.XAxis(showgrid=False, zeroline=False), yaxis=pygo.YAxis(showgrid=False, zeroline=False)) fig = pygo.Figure(data=data, layout=layout) plot_url = py.plot(fig, filename='catcorr_'+mode)