简体   繁体   中英

NetworkX Plot Titles - Interactive Plots

I've been following a tutorial for visualising multicollinearity and have been building an interactive network graph. I would like to add a title to the plot and I found this SO question which I thought would help, however it is not about an interactive plot and when I try the answers, I end up with my same interactive graph with no title, and then a small empty non interactive plot below with a title.

My code currently looks like:

plt.title('Network Graph Showing Correlated Metabolites at Adjustable Correlation Thresholds')
threshold_choice = widgets.FloatSlider(description="Threshold", value=0.8, min=0.1, max=1, step=0.05, 
                                    continuous_update=False, orientation='horizontal', layout=Layout(width='500px'), 
                                    style=dict(description_width= 'initial'))

network = go.FigureWidget(data=[go.Scatter(x=[], y=[], mode='lines', text=[],  line=dict(color='#cc78bc', width=2.5), 
                                    marker=dict(size=16, line_width=5,line=dict(color='#cc78bc',width=2))),
                                    go.Scatter(x=[], y=[],mode='markers+text', textposition="top center", text=[], 
                                    hoverinfo='text',textfont_size=12, marker=dict(size=10, color=[],line_width=1))],
                                    layout=go.Layout( showlegend=False, annotations=[], margin=dict(t=40, b=0, l=0, r=0), 
                                    width=950, height=800))
df = AlzZ.copy()
correlation_matrix = cor.to_numpy()

def plot_corr_graph(change):
    threshold, corr_mode = None, None
    threshold = change.new
    
    tr_ind = np.triu_indices(correlation_matrix.shape[0])
    correlation_matrix[tr_ind] = 0
    G = nx.from_numpy_matrix(correlation_matrix)
    G = nx.relabel_nodes(G, lambda x: df.columns.tolist()[x])
   
    remove = []
    
    for col1, col2, weight in G.edges(data=True):
      if math.isnan(weight["weight"]):
        remove.append((col1,col2))
    
      if abs(weight["weight"]) < threshold:
        remove.append((col1,col2))
    
    G.remove_edges_from(remove)
    
    remove = []
    edges = list(sum(G.edges, ()))
    
    for node in G.nodes:
      if node not in edges:
        remove.append(node)
    G.remove_nodes_from(remove)
    mst = nx.maximum_spanning_tree(G)
    
    def assign_color(col):
      return colorlistMCLN

    def assign_color_edge(correlation):
      if correlation < 0:
        return "#BF0603"
      else:
        return "#00CC66"
    edge_colors = []
    node_colors = []
    for key, value in nx.get_edge_attributes(mst, 'weight').items():
        edge_colors.append(assign_color_edge(value))
    for key, value in dict(mst.degree).items():
        node_colors.append(assign_color(key))
      
    labels = {n:n for n in mst.nodes()}
    node_x = []
    node_y = []
    
    tree = nx.fruchterman_reingold_layout(mst, k=0.25).items()
    
    for node, (x_,y_) in tree:
        node_x.append(x_)
        node_y.append(y_)
        
    def get_dim_of_node(name):
        for node, (x,y) in tree:
            if node == name:
                return x,y
        
    edge_x = []
    edge_y = []
    
    weights= []
    for node1, node2, w in mst.edges(data=True):
        x0, y0 = get_dim_of_node(node1)
        x1, y1 =  get_dim_of_node(node2)
        edge_x.append(x0)
        edge_x.append(x1)
        edge_x.append(None)
        edge_y.append(y0)
        edge_y.append(y1)
        edge_y.append(None)
        weights.append((round(w["weight"],1), (x0+x1)/2, (y0+y1)/2))
                              
    with network.batch_update():
        network.data[1].x = node_x
        network.data[1].y = node_y
        network.data[1].text = list(labels)
        network.data[1].marker.color = node_colors
                          
        network.data[0].x = edge_x
        network.data[0].y = edge_y
        network.data[0].text = list(weights)
        network.update_layout(xaxis_zeroline=False, yaxis_zeroline=False, xaxis_showgrid=False, yaxis_showgrid=False, 
                              plot_bgcolor='rgba(0,0,0,0)')

threshold_choice.observe(plot_corr_graph, names="value")
widgets.VBox([threshold_choice, network])

With my output looking like: output image

I've also tried putting

plt.title('title')

between the threshold_choice object and the network object, and have tried

ax = plt.gca()
ax.set_title('title')

below the correlation_matrix object - which has the same result.

When I place it within the function, below the threshold object it which did not produce any plots with titles, just the original network graph.

I've figured it out:

The issue is the interactive graph is not actually a plot at all from the perspective of the code. It is a FigureWidget . Knowing this makes it much easier to find the right documentation.

Initially I had been looking here: NetworkX Documentation

However you actually need to be looking at this page in the plotly documentation.

In the example above (in the question) it means changing the network object to this:

network = go.FigureWidget(data=[go.Scatter(x=[], y=[], mode='lines', text=[],  line=dict(color='#cc78bc', width=2.5), 
                                    marker=dict(size=16, line_width=5,line=dict(color='#cc78bc',width=2))),
                                    go.Scatter(x=[], y=[],mode='markers+text', textposition="top center", text=[], 
                                    hoverinfo='text',textfont_size=12, marker=dict(size=10, color=[],line_width=1))],
                                    layout=go.Layout(showlegend=False, annotations=[], margin=dict(t=40, b=0, l=0, r=0), 
                                    width=950, height=800, title='Network Graph Showing Correlated Metabolites at Adjustable Correlation Thresholds')) 

The title gets included in the layout argument as title='your title'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM