def ds_plot(G, layout='circular', method='direct', bw=0.05, name='', kwargs=cvsopts): ''' Returns graph plot using datashader layout fir nodes positions from circular (default), forceatlas2 or random position layout. Accepted vars: G => network graph obj layout => circular; forceatlas2; random method => connect; bundle bw => initial bandwith for bundled name => title or label ''' n, e = nx_layout(G) nodes = ds_layout(n, e, layout) if method == 'bundle': edges = hammer_bundle(nodes, e, initial_bandwidth=bw) else: # lightweight edges = connect_edges(nodes, e) return graph_plot(nodes, edges, name, kwargs=kwargs)
def newPlotlyGeneration(relayoutData): f = go.Figure(data=[{'x': [relayoutData['xaxis.range[0]'], relayoutData['xaxis.range[1]']], 'y': [relayoutData['yaxis.range[0]'], relayoutData['yaxis.range[1]']], 'mode': 'markers', 'marker': {'opacity': 0}}], # invisible trace to init axes and to support autoresize layout={'width': 800, 'height': 600} ) newImg = newGraphplot(fd, connect_edges(fd,edges), x_range=[relayoutData['xaxis.range[0]'], relayoutData['xaxis.range[1]']], y_range=[relayoutData['yaxis.range[0]'], relayoutData['yaxis.range[1]']]) newPil = tf.Image(newImg).to_pil() #in_mem_file = io.BytesIO() #newPil.save(in_mem_file, format = "PNG") # reset file pointer to start #in_mem_file.seek(0) #img_bytes = in_mem_file.read() #base64_encoded_result_bytes = base64.b64encode(img_bytes) #base64_encoded_result_str = base64_encoded_result_bytes.decode('ascii') f.layout.images = [go.layout.Image( source = newPil, # plotly now performs auto conversion of PIL image to png data URI xref = "x", yref = "y", x = relayoutData['xaxis.range[0]'], y = relayoutData['yaxis.range[1]'], sizex = relayoutData['xaxis.range[1]'] - relayoutData['xaxis.range[0]'], sizey = relayoutData['yaxis.range[1]'] - relayoutData['yaxis.range[0]'], #sizing = "stretch", layer = "below")] return f
def zoomButton(): jsonResp = request.get_json() cvsopts['plot_height'] = int(jsonResp["height"]) cvsopts['plot_width'] = int(jsonResp["width"]) current_x_range = tuple( (float(jsonResp["current_x_low"]), float(jsonResp["current_x_high"]))) current_y_range = tuple( (float(jsonResp["current_y_low"]), float(jsonResp["current_y_high"]))) current_y_low, current_y_high = current_y_range[0], current_y_range[1] current_x_low, current_x_high = current_x_range[0], current_x_range[1] dsPlot = newGraphplot(randomloc, connect_edges(randomloc, edges), x_range=current_x_range, y_range=current_y_range) #convert datashder image to png back_img = tf.Image(dsPlot).to_pil() in_mem_file = io.BytesIO() back_img.save(in_mem_file, format="PNG") # reset file pointer to start in_mem_file.seek(0) img_bytes = in_mem_file.read() base64_encoded_result_bytes = base64.b64encode(img_bytes) base64_encoded_result_str = 'data:image/png;base64,' + base64_encoded_result_bytes.decode( 'ascii') return jsonify(newImage=base64_encoded_result_str, x_low=current_x_range[0], y_low=current_y_range[0], x_high=current_x_range[1], y_high=current_y_range[1])
def nx_plot(graph, name=""): print(graph.name, len(graph.edges)) nodes, edges = nx_layout(graph) direct = connect_edges(nodes, edges) bundled_bw005 = hammer_bundle(nodes, edges) bundled_bw030 = hammer_bundle(nodes, edges, initial_bandwidth=0.30) return [ graphplot(nodes, direct, graph.name), graphplot(nodes, bundled_bw005, "Bundled bw=0.05"), graphplot(nodes, bundled_bw030, "Bundled bw=0.30") ]
def zoomButton(): jsonResp = request.get_json() cvsopts['plot_height'] = int(jsonResp["height"]) cvsopts['plot_width'] = int(jsonResp["width"]) current_x_range = tuple((float(jsonResp["current_x_low"]), float(jsonResp["current_x_high"]))) current_y_range = tuple((float(jsonResp["current_y_low"]), float(jsonResp["current_y_high"]))) current_y_low, current_y_high = current_y_range[0], current_y_range[1] current_x_low, current_x_high = current_x_range[0], current_x_range[1] dsPlot = newGraphplot(randomloc, connect_edges(randomloc,edges), x_range=current_x_range, y_range=current_y_range) #convert datashder image to png back_img = tf.Image(dsPlot).to_pil() in_mem_file = io.BytesIO() back_img.save(in_mem_file, format = "PNG") # reset file pointer to start in_mem_file.seek(0) img_bytes = in_mem_file.read() base64_encoded_result_bytes = base64.b64encode(img_bytes) base64_encoded_result_str = 'data:image/png;base64,' + base64_encoded_result_bytes.decode('ascii') return jsonify(newImage=base64_encoded_result_str, x_low=current_x_range[0], y_low=current_y_range[0], x_high=current_x_range[1], y_high=current_y_range[1])
def plot_graph(self, method='networkx', options={}): digr = self.make_graph() if method == 'networkx': dflt_options = { 'node_color': 'black', 'node_size': 20, 'width': 1, } opts = {**dflt_options, **options} nx.draw_kamada_kawai(digr, **opts) elif method == 'datashader': digr = digr.to_undirected() nodes = pd.DataFrame(digr.nodes(), columns=['name']) edges = pd.DataFrame(digr.edges(), columns=['source', 'target']) iterations = { 'iterations': int(np.ceil(np.sqrt(len(nodes)))), **options }['iterations'] fd = forceatlas2_layout(nodes, edges, iterations=iterations) bundle = {'bundle': False, **options}['bundle'] if bundle: return graphplot(fd, hammer_bundle(fd, edges)) else: return graphplot(fd, connect_edges(fd, edges))
#combines nodes and edges in datashader image def graphplot(nodes, edges, name="", canvas=None, cat=None): if canvas is None: xr = nodes.x.min(), nodes.x.max() yr = nodes.y.min(), nodes.y.max() canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts) np = nodesplot(nodes, name + " nodes", canvas, cat) #print(np) ep = edgesplot(edges, name + " edges", canvas) #print(ep) return tf.stack(ep, np, how="over", name=name) fd = forcedirected fd_d = graphplot(fd, connect_edges(fd,edges)) #convert datashder image to png back_img = tf.Image(fd_d).to_pil() x_range=fd.x.min(), fd.x.max() y_range=fd.y.min(), fd.y.max() #xr = nodes.x.min(), nodes.x.max() #yr = nodes.y.min(), nodes.y.max() plot_height=600 plot_width=800 #Create initial plotly graph with datashader image as background
name="", canvas=None, cat=None, margin=0.05): if canvas is None: xr = nodes.x.min() - margin, nodes.x.max() + margin yr = nodes.y.min() - margin, nodes.y.max() + margin canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts) np = my_nodesplot(nodes, name + " nodes", canvas, cat) ep = edgesplot(edges, name + " edges", canvas) return tf.stack(ep, np, how="over", name=name) forcedirected = forceatlas2_layout(nodes, edges) fd = forcedirected fd.iat[0, 2] = (fd.x.min() + fd.x.max()) / 2 # center focus node on x fd.iat[0, 3] = 1 # center focus node on y ## save image?! image = tf.Image( my_graphplot(fd, connect_edges(fd, edges), "Force-directed", cat="type", margin=0.02)) export_image(image, filename=file) os.rename(file_name, saved_file_name)
#Tedges.head() Tedges.source = pd.to_numeric(Tedges.source) Tedges.target = pd.to_numeric(Tedges.target) # In[9]: #Tedges.isnull().values.any() Tnodes = adrs[['GEO_ID', 'LATITUDE', 'LONGITUDE']] Tnodes.columns = ['id', 'x', 'y'] Tnodes.set_index('id', inplace=True) #Tnodes.head() #location2.loc["GEOID","LATITUDE", "LONGITUDE"]] # In[10]: direct = connect_edges(Tnodes, Tedges[['source', 'target']]) # In[28]: location2.COORDS2 # In[32]: # ============================================================================= # Plotting with Holoview and Datashade # ============================================================================= get_ipython().magic(u'output size=150') points = hv.Points((location2.LATITUDE, location2.LONGITUDE), label="Buildings") paths = hv.Path([direct])
def my_graphplot(nodes, edges, name="", canvas=None, cat=None, margin=0.05): if canvas is None: xr = nodes.x.min() - margin, nodes.x.max() + margin yr = nodes.y.min() - margin, nodes.y.max() + margin canvas = ds.Canvas(x_range=xr, y_range=yr, **cvsopts) np = my_nodesplot(nodes, name + " nodes", canvas, cat) ep = edgesplot(edges, name + " edges", canvas) return tf.stack(ep, np, how="over", name=name) forcedirected = forceatlas2_layout(nodes, edges) fd = forcedirected fd.iat[0,2] = (fd.x.min() + fd.x.max())/2 # center focus node on x fd.iat[0,3] = 1 # center focus node on y ## save image?! from datashader.utils import export_image image = tf.Image(my_graphplot(fd, connect_edges(fd,edges), "Force-directed", cat="type", margin=0.02)) file = company_name.replace(" ","_") export_image(image, filename=file) import os file_name = file + ".png" os.rename(file_name, '../../ent-out/' + file_name)