def explicitPathHoloviewsGraph(): hv.extension('bokeh') #%opts Graph [width=400 height=400] N = 8 node_indices = np.arange(N) #using index as indicator of the node number #source reveals the point of departure a1 source = np.zeros( N ) #every edge starts from node 0 - numpy array of zeros : [0. 0. 0. 0. 0. 0. 0. 0.] #target reveals the point of arrival a2 target = node_indices #numpy array of range : [0 1 2 3 4 5 6 7] padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) #X and Y showed scale on the cartesian table simple_graph = hv.Graph(((source, target), )).redim.range(**padding) def bezier(start, end, control, steps=np.linspace(0, 1, 100)): return (1 - steps)**2 * start + 2 * ( 1 - steps) * steps * control + steps**2 * end x, y = simple_graph.nodes.array([0, 1]).T paths = [] for node_index in node_indices: ex, ey = x[node_index], y[node_index] paths.append( np.column_stack([bezier(x[0], ex, 0), bezier(y[0], ey, 0)])) bezier_graph = hv.Graph( ((source, target), (x, y, node_indices), paths)).redim.range(**padding) hv.renderer('bokeh').save(bezier_graph, 'out')
def hv_plot(G, layout='circular', method='bokeh', name='', kwargs=opts): ''' Returns graph plot using HoloViews wrapper for bokeh. Optionally, draws edges using datashade functions. Accepted vars: G => networkx.Graph() object layout => circular; forceatlas2; random method => bokeh; datashader name => graph title or label kwargs => optionals ''' hv.extension("bokeh") nodes, edges = nx_layout(G) # apply parameters if kwargs: hv.opts.defaults( hv.opts.EdgePaths(**kwargs), hv.opts.Graph(**kwargs), hv.opts.Nodes(**kwargs)) # plot edges with bokeh circle = hv.Graph(edges, label=name).opts(style=dict(node_size=10)) # plot edges with datashader (WIP) if method == 'datashader': hnodes = circle.nodes.opts(style=dict(size=10)) dscirc = (hd.dynspread(hd.datashade(circle))*hnodes).relabel(name) return dscirc return circle
def _graph(edges, node_positions, info_df=None, cluster_column=None): # have to add clusters explicitly if isinstance(cluster_column, np.ndarray): info_df = info_df.copy() info_df["node_color"] = cluster_column.astype(int) nodes = _nodes(node_positions, info_df) source, target = edges.T graph = hv.Graph(((source, target), nodes)) return graph
def myGraphTestSpringLayout2(): hv.extension('bokeh') renderer = hv.renderer('bokeh') #EXAMPLE GRAPH EDGE LIST path = "/u/alfonsda/Documents/DOCTORAT_TAL/004projetOntologie/holoviews-examples/myGraphEdgeList.tsv" #100 000 PROFILES GRAPH EDGE LIST #path = "/u/alfonsda/Documents/DOCTORAT_TAL/004projetOntologie/002data/candidats/2016-09-15/fr/anglophone/sample100milFunctions/edgeListNoWeight.tsv" g = nx.read_edgelist( path, delimiter='\t', nodetype=str, data=(('weight', float), ('index', int))) #the bigger the edgelist weight appears shorter #set colors for the nodes nodeColorsDict = getNodeColors(path) nx.set_node_attributes(g, name='color', values=nodeColorsDict) #position nodes using Fruchterman-Reingold force-directed algorithm #pos = nx.spring_layout(g, weight='weight', iterations=50, scale=2, center=(0,0)) #nodes = hv.Nodes((x, y, node_indices, node_labels), vdims='Type') myGraph = hv.Graph.from_networkx( g, nx.spring_layout, nodes=None, weight='weight', iterations=50, scale=2, center=(0, 0) ) #the spring layout uses Fruchterman-Reingold force-directed algorithm to lay out the graph myGraph = hv.Graph( myGraph, label= 'Graphe echantillon (EDGES: 795046, VERTICES : JobTitles(3827) - Skills(7529)' ) #nodes = hv.Nodes((x, y, node_indices, node_labels), vdims='Type') #print(myGraph.nodes['index']) padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) #X and Y showed scale on the cartesian table #myGraph = myGraph.redim.range(**padding).opts(plot=dict(height=800, width=1000, color_index='Type', edge_color_index='Weight'), # style=dict(node_fill_color='red', cmap=['green', 'red'])) myGraph = myGraph.redim.range(**padding).opts( plot=dict(height=800, width=1000, node_fill_color='color', edge_color_index='Weight'), style=dict(cmap=nodeColorsDict)) interactImg = InteractiveImage(myGraph, create_image()) #myGraph = rasterize(myGraph) renderer.save(interactImg, 'out')
def get_graph_from_data(node_and_edges_data): node_data = node_and_edges_data['node_data'] source_edges = node_and_edges_data['source_edges'] target_edges = node_and_edges_data['target_edges'] node_data['minus_mean_deviation'] = -node_data['mean_deviation'] nodes = hv.Nodes(data=node_data) tooltips = [('Samples', '@samples'), ('Mean Deviation', '@mean_deviation'), ('Index', '@index'), ('Partition', '@partition')] hover = HoverTool(tooltips = tooltips) # add labels to nodes labels = hv.Labels(nodes, ['x', 'y'], 'index') graph = hv.Graph(((source_edges, target_edges), nodes)).opts( node_color='mean_deviation', cmap='viridis', node_size = 'node_sizes', tools=[hover], hooks=[hook_graph], height = 600, responsive = True, xaxis = None, yaxis=None) # add text to the right of the graph indicating the quartiles xpos = np.max(node_data['x']) ypos = list(set(node_data['y'])) ypos.sort() quartile_texts = ['All', 'Lower Quartile', '2nd Quartile', '3rd Quartile', 'Higher Quartile '] labels_quartiles = hv.Labels({'x' : xpos, 'y' : ypos, 'text' : quartile_texts }, ['x','y'], 'text') labels_quartiles.opts(xoffset = 1, align='start') # TODO: append the quartile texts to the plot final_graph = graph * labels #final_graph.opts( # opts.Labels(text_color='y', cmap='BrBG', color_levels=5)) return final_graph
def render_graphs(input_df, layer): padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) purchase_row = my_data.loc[my_data['Etype'] == 5].iloc[0] title_graph = '{} Layer {}'.format(purchase_row['Source_Names'], layer) simple_graph = hv.Graph( ((input_df['Source_Names'], input_df['Destination_Names']), ), label=title_graph).redim.range(**padding) simple_graph() simple_graph.options(inspection_policy='edges', show_title=True) #hv.Layout([simple_graph.relabel(label=title)]) hv.renderer('bokeh').server_doc(simple_graph)
def myGraphTest(): graphData = pd.read_csv('./myGraph.tsv', sep='\t') source = graphData['jobTitleNodeIndex'].values sourceLabels = graphData['jobTitleName'].values target = graphData['skillNodeIndex'].values targetLabels = graphData['skillName'].values padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) #X and Y showed scale on the cartesian table myGraph = hv.Graph(((source, target), )).redim.range(**padding) hv.renderer('bokeh').save(myGraph, 'out')
def simpleHoloviewsGraph(): hv.extension('bokeh') #%opts Graph [width=400 height=400] N = 8 node_indices = np.arange(N) #using index as indicator of the node number #source reveals the point of departure a1 source = np.zeros( N ) #every edge starts from node 0 - numpy array of zeros : [0. 0. 0. 0. 0. 0. 0. 0.] #target reveals the point of arrival a2 target = node_indices #numpy array of range : [0 1 2 3 4 5 6 7] padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) #X and Y showed scale on the cartesian table simple_graph = hv.Graph(((source, target), )).redim.range(**padding) hv.renderer('bokeh').save(simple_graph, 'out') return
def plot(self): dftoplot = self.networkdf() nodelist = list( set(dftoplot['Senders'].tolist() + dftoplot['Receivers'].tolist())) node_labels = list( map(lambda addr: 1 if addr == self.address else 0, nodelist)) nodedf = pd.DataFrame({'nodes': nodelist, 'label': node_labels}) padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) node_info = hv.Dataset(nodedf, vdims='label') graph = hv.Graph((dftoplot, node_info)).redim.range(**padding) graphtoplot = graph.opts(plot=dict(width=800,height=600,\ color_index='label', edge_color_index='isoriginal',\ cmap='Set1', edge_cmap='viridis',inspection_policy='edges')) return renderer.get_plot(graphtoplot).state
def plot2(self): dftoplot = self.networkdf() nodelist = list( set(dftoplot['Sender'].tolist() + dftoplot['Recipient'].tolist())) node_labels = list( map(lambda addr: 1 if addr == self.address else 0, nodelist)) nodedf = pd.DataFrame({'nodes': nodelist, 'label': node_labels}) padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) node_info = hv.Dataset(nodedf, vdims='label') graph = hv.Graph( (dftoplot[['Sender', 'Recipient', 'Bitcoin Sent']], node_info)).redim.range(**padding) renderer = hv.renderer('bokeh') graphtoplot = graph.opts(plot=dict(width=800,height=600,xaxis=None,yaxis=None,\ color_index='label', edge_color_index='Bitcoin Sent',inspection_policy='edges'),\ style=dict(cmap=['blue','green'], edge_cmap='plasma',inspection_policy='edges')) return renderer.get_plot(graphtoplot).state
If you have any issue or questions, please either raise an [issue on github](https://github.com/chronchi/ttmap-app/issues) or [mail me](mailto:[email protected]) """ how_to_use_it = pn.Column(pn.pane.Markdown(how_to_use, sizing_mode='stretch_both'), sizing_mode='stretch_both', scroll = True) dataframe_and_query = pn.Column(query_dropdown, query_box, pn.Row(download_table_graph_button, download_graph_button, align='center'), hv.Table(pd.DataFrame({})).opts(width=300), width = 300, ) final_display = pn.Row(hv.Graph(()).opts(xaxis=None, yaxis=None, responsive=True), dataframe_and_query, sizing_mode = 'stretch_both' ) significant_genes_analysis = pn.Column(query_box_deviated_genes, query_genes, download_significant_components_button, pn.Spacer(), sizing_mode = 'stretch_both') final_display = pn.Tabs(('How to use ttmap', how_to_use_it), ('Two-Tier Mapper', final_display), ('Outlier Analysis', pn.GridSpec()), ('Significant Components', significant_genes_analysis)) width_first_column = 290 pn_spacer = 1
# use natural logarithm of edge weight, for visualization purposes edges_df['weight'] = np.log(edges_df['weight'].astype(float)) # scale edge weight for visualization purposes edges_df['weight'] /= EDGE_SCALING # 4. generate visualization using HoloViews package ############################################################################# # convert node DataFrame to HoloViews object hv_nodes = hv.Nodes(nodes_df).sort() # create HoloViews Graph object from nodes and edges, with x and y limits # bounded by `GRAPH_EXTENTS` hv_graph = hv.Graph((edges_df, hv_nodes), extents=GRAPH_EXTENTS) # define custom hover tooltip hover = HoverTool(tooltips=[ ("member id", "@member_id"), ("name", "@name"), ("posts", "@posts"), ("messages", "@messages"), ]) # specify parameters for visualization hv_graph.opts(node_radius='size', edge_color='white', node_color='#ff9c03', node_hover_fill_color='#EF4E02', edge_alpha=0.2,
import numpy as np import pandas as pd import holoviews as hv from holoviews import opts hv.extension('bokeh') # Declare abstract edges N = 8 node_indices = np.arange(N, dtype=np.int32) source = np.zeros(N, dtype=np.int32) target = node_indices print(source, target) simple_graph = hv.Graph(((source, target), )) simple_graph
def plot(): df_data = pd.read_csv(file, sep=';', header=0, index_col=False) p = [] d = [] e = [] f = [] hold = df_data.shape[0] # loop that sets values first in lists for columns l = 0 i = 0 while i < hold: # Fromnames + delete row of names once listed b = list(df_data.columns.values) del b[0] a1 = len(b) - (i - 1) a = list(a1 * (df_data.iloc[i, 0], )) del a[:1] # Tonames + delete names that are already linked p = b del p[:(i)] # weights + delete weights that are already linked c = df_data.iloc[0:, (i + 1)].tolist() del c[:(i)] # remove people linked to themselves # for ele in c: # if ele == 1: # c.remove(ele) e = list(e + a) d = list(d + p) f = list(f + c) i += 1 # df from which the plot will be made df_plot = pd.DataFrame(columns=['from', 'to', 'weight']) # puts said lists in columns df_plot['from'] = e df_plot['to'] = d df_plot['weight'] = f df_plot = df_plot.loc[df_plot['weight'] != 0.0] check = df_plot['from'] == df_plot['to'] check2 = df_plot['weight'] == 1 df_plot = df_plot[(check == False) & (check2 == False)] df_plot.reset_index() graph = hv.Graph(df_plot) graph.opts(width=900, height=900, show_frame=False, edge_color='weight', xaxis=None, yaxis=None, node_size=10, edge_line_width='weight') # layout of graph layout_nodes(graph, layout=nx.layout.fruchterman_reingold_layout, kwargs={'weight': 'weight'}) holder = graph renderer = hv.renderer('bokeh') k = renderer.get_plot(holder).state k.plot_width = 700 k.plot_height = 700 # graph = from_networkx(G, nx.spring_layout, scale=2, center=(0, 0) return json.dumps(json_item(k))
# Chord diagram with interactive components edgeList = edges[['Source', 'Target', 'weight']] nodeDS = hv.Dataset(nodes, 'Id') chord = hv.Chord((edgeList, nodeDS)) chord.opts( opts.Chord(inspection_policy='nodes', tools=['hover'], edge_hover_line_color='green', node_hover_fill_color='red')) hv.save(chord, 'simple_chord.html') # Coloured interactive chord diagram kwargs = dict(width=300, height=300, xaxis=None, yaxis=None) opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs)) graph = hv.Graph((edgeList, nodeDS), label='GoT season 1') graph.opts(cmap='Category20', edge_cmap='Category20', node_size=10, edge_line_width=1, node_color=dim('Id').str(), edge_color=dim('Source').str()) hv.save(graph, 'coloured_chord.html') # Facebook data as graph with predifined coordinate system kwargs = dict(width=300, height=300, xaxis=None, yaxis=None) opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs)) colors = ['#000000'] + hv.Cycle('Category20').values
edf = pd.DataFrame(el) # make sure there aren't any edges that go to a nonexistant node edf = edf[((edf['start'].isin(ndf['user index'])) & (edf['stop'].isin(ndf['user index'])))] # create graph and save #----------------------------------------------------------------------------# # initialize default args for Holoviews kwargs = dict(width=600, height=600, xaxis=None, yaxis=None) opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs)) # construct Holoviews graph with Bokeh backend hv_nodes = hv.Nodes(ndf).sort() hv_graph = hv.Graph((edf, hv_nodes)) hv_graph.opts(node_color='log degree', node_size=10, edge_line_width=1, node_line_color='gray', edge_hover_line_color='#DF0000') # bundle edges for aestheticss bundled = bundle_graph(hv_graph) # save html of interactive visualizations renderer.save(bundled, 'ff_reaction_graph_bundled') renderer.save(hv_graph, 'ff_reaction_graph') #----------------------------------------------------------------------------#
def _make_progress(self): import holoviews as hv import holoviews.plotting.bokeh # noqa if self._graph: root = get_root(self._graph) depth = get_depth(root, self._graph) breadths = get_breadths(root, self._graph) max_breadth = max(len(v) for v in breadths.values()) else: root = None max_breadth, depth = 0, 0 breadths = {} height = 80 + (max_breadth - 1) * 20 edges = [] for src, tgts in self._graph.items(): for t in tgts: edges.append((src, t)) nodes = [] for depth, subnodes in breadths.items(): breadth = len(subnodes) step = 1. / breadth for i, n in enumerate(subnodes[::-1]): if n == self._stage: state = 'active' elif n == self._error: state = 'error' elif n == self._next_stage: state = 'next' else: state = 'inactive' nodes.append((depth, step / 2. + i * step, n, state)) cmap = { 'inactive': 'white', 'active': '#5cb85c', 'error': 'red', 'next': 'yellow' } def tap_renderer(plot, element): from bokeh.models import TapTool gr = plot.handles['glyph_renderer'] tap = plot.state.select_one(TapTool) tap.renderers = [gr] nodes = hv.Nodes(nodes, ['x', 'y', 'Stage'], 'State').opts(alpha=0, default_tools=['tap'], hooks=[tap_renderer], hover_alpha=0, selection_alpha=0, nonselection_alpha=0, axiswise=True, size=10, backend='bokeh') self._progress_sel.source = nodes graph = hv.Graph((edges, nodes)).opts(edge_hover_line_color='black', node_color='State', cmap=cmap, tools=[], default_tools=['hover'], selection_policy=None, node_hover_fill_color='gray', axiswise=True, backend='bokeh') labels = hv.Labels(nodes, ['x', 'y'], 'Stage').opts(yoffset=-.30, default_tools=[], axiswise=True, backend='bokeh') plot = (graph * labels * nodes) if self._linear else (graph * nodes) plot.opts(xaxis=None, yaxis=None, min_width=400, responsive=True, show_frame=False, height=height, xlim=(-0.25, depth + 0.25), ylim=(0, 1), default_tools=['hover'], toolbar=None, backend='bokeh') return plot
edges_df['source'] = edges_df['source'].map(unique_to_idx) edges_df['target'] = edges_df['target'].map(unique_to_idx) # Color each edge according to its nodes edges_df['color'] = edges_df.apply(get_edge_color, axis=1) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++# # Convert edge and node DataFrames into Holoviews graph, define tooltips #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++# # Convert node DataFrame to HoloViews object hv_nodes = hv.Nodes(nodes_df) # Create HoloViews Graph object from nodes and edges, with x and y limits # bounded by `GRAPH_EXTENTS` hv_graph = hv.Graph((edges_df, hv_nodes), ) # Define custom hover tooltip hover = HoverTool(tooltips=[ ('Officer Name', '@FullName'), ('ID', '@IdNumber'), ('Company 1', '@Company1'), ('Company 2', '@Company2'), ('Company 3', '@Company3'), ]) #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++# # Define configuration options for visualization, and render visualization #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++# # Specify Holoviews options
def plot_subgraph(csv_path, rel_name): global edges_plot global nodes_plot global node_type_size_dict global labels with open(csv_path, 'r') as w: data = pd.read_csv(w) if not (os.path.exists(f'./{rel_name}')): os.mkdir(f'./{rel_name}') if not (os.path.exists(f'./{rel_name}/subgraphs')): os.mkdir(f'./{rel_name}/subgraphs') #this is since I have CSV that does not explicitly specify node types data["left"] = data.Edge.apply(lambda a: a.split("-->")[0]) data["right"] = data.Edge.apply(lambda a: a.split("-->")[1]) #get all unique nodes nodes = pd.concat([data.left,data.right],ignore_index=True).drop_duplicates().reset_index(drop=True).to_frame("name").reset_index() data["left_index"] = nodes.set_index("name").loc[data.left,"index"].values data["right_index"] = nodes.set_index("name").loc[data.right,"index"].values #also temporary type should be in the csv nodes["type"] = nodes.name.apply(lambda a: "Chem/Gene" if a in data.left.values else "Disease") # ### Create NetworkX Graph # Make a directed graph from a list of edges. # Also let's compute node layout as well... layout is just position of every node on the canvas graph = nx.DiGraph() graph.add_edges_from(data.loc[:,["left_index","right_index"]].values) layout = nx.layout.fruchterman_reingold_layout(graph.to_undirected(),.5) layout = pd.DataFrame(layout,index=["x","y"]).T.sort_index() nodes = pd.concat([nodes,layout],axis=1) # ## Let's Plot Some Graphs paths = make_paths(nodes,data) hv.extension("bokeh") nodes_plot = hv.Nodes(nodes,kdims=["x","y","index"],vdims=["name","type"]).opts(show_legend=True) edges_plot = hv.Graph((data,nodes_plot,paths),kdims=["left_index","right_index"],vdims=["Original_Weight","Boltzmann_Citation_Weight","Publication_Year_Weight","Publication_Year_and_Citation_Weight", "H_Index_Weight"]) # edges_plot = bundle_graph(edges_plot) labels = hv.Labels(nodes,kdims=["x","y"],vdims=["name"]).opts(text_align="left", text_font_size="8pt",xoffset=.05,text_alpha = .5, text_color="white") weight_field = "Boltzmann_Citation_Weight" weights = ["Original_Weight","Boltzmann_Citation_Weight","Publication_Year_Weight","Publication_Year_and_Citation_Weight", "H_Index_Weight"] # need to change this node_type_size_dict = {"Chem/Gene":15,"Disease":30} out = hv.HoloMap({w: make_plot(w) for w in weights},kdims = "weight_type") print('Saving Subgraphs to file...') hv.save(out,f"./{rel_name}/subgraphs/{rel_name}_subgraph.html") hv.save(out,f"./{rel_name}/subgraphs/{rel_name}_img1.gif") # ![Subgraph](imgs/img1.gif) # We can also see all of them side by side out2 = out.opts(width=600,height=600).layout("weight_type").cols(2) hv.save(out2,f"./{rel_name}/subgraphs/{rel_name}_img2.png") hv.save(out2,f"./{rel_name}/subgraphs/{rel_name}_subgraph_side_by_side.html")
# Specify the plot render to use hv.extension('bokeh') hv.output(size=300) # Chord diagram with interactive components edgeList = edges[['Source', 'Target', 'weight']] # Within the holoviews dataset object we define kdim and vdims # Kdims are the independent variables which is Id in this example # Vdims are dependent variables cent_value and rank_value # By defining these here were can use them when creating the graph nodeDS = hv.Dataset(nodes_extended, 'Id', ['cent_value', 'rank_value']) # Coloured interactive chord diagram with node size determined by Vdims kwargs = dict(width=300, height=300, xaxis=None, yaxis=None) opts.defaults(opts.Nodes(**kwargs), opts.Graph(**kwargs)) graph = hv.Graph((edgeList, nodeDS), label='GoT season 1') graph.opts(cmap='Category20', edge_cmap='Category20', node_size='cent_value', edge_line_width=1, node_color=dim('Id').str(), edge_color=dim('Source').str()) graph.opts( opts.Chord(inspection_policy='nodes', tools=['hover'], edge_hover_line_color='green', node_hover_fill_color='red')) hv.save(graph, 'node_size_chord.html')
#Create empty graph dillaGraph = nx.Graph() numNodes = 0 #Add edges to graph for entry in edgeList: i = 0 j = 1 dillaGraph.add_edge(entry[i], entry[j]) numNodes += 1 #For Display Purposes padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) #Create hoverable Graph node_labels = ['Test'] * (numNodes + 1) node_info = hv.Dataset(node_labels, vdims='Label') dillaGraph = hv.Graph.from_networkx( dillaGraph, nx.layout.spring_layout).redim.range(**padding) dillaGraph = hv.Graph( (dillaGraph), label='JDilla Sampled Song Network Graph').redim.range(**padding).options( width=1000, height=1000) #For exportation Purposes renderer = hv.renderer('bokeh') dillaGraph = renderer.get_plot(dillaGraph).state show(dillaGraph)