[Python] make matplotlib plot interactive with Dash

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    I found this thread shows how to create and visualise a directed weighted graph. I improved on the answer provided there, slightly:

    import random
    import networkx as nx
    import matplotlib.pyplot as plt
    from netgraph import MultiGraph

    def create_graph_from_data(nodes, edges):
    G = nx.MultiDiGraph()

    # Add nodes from the provided list
    G.add_nodes_from(nodes)

    # Add edges from the provided list of tuples (node1, node2, weight)
    for (node1, node2, weight) in edges:
    G.add_edge(node1, node2, weight=weight)

    return G

    # Example usage:
    nodes = [0, 1, 2, 3, 4] # Custom list of nodes
    edges = [
    (0, 1, 5), # Edge from node 0 to node 1 with weight 5
    (1, 2, 3), # Edge from node 1 to node 2 with weight 3
    (2, 3, 2), # Edge from node 2 to node 3 with weight 2
    (3, 4, 4), # Edge from node 3 to node 4 with weight 4
    (4, 0, 6), # Edge from node 4 to node 0 with weight 6
    (0, 2, 7), # Edge from node 0 to node 2 with weight 7
    (1, 4, 8) # Edge from node 1 to node 4 with weight 8
    ]

    # Create the graph from the custom nodes and edges
    G = create_graph_from_data(nodes, edges)

    # Display the graph
    MultiGraph(
    G,
    node_labels=True,
    node_color="skyblue",
    edge_color="gray",
    edge_labels=nx.get_edge_attributes(G, 'weight'),
    edge_label_fontdict=dict(fontsize=8),
    arrows=True,
    )
    plt.show()


    Is there a way to make this interactive on Dash? I want to eventually be able to say: show me only nodes 0, 2 and 3.

    Continue reading...

Compartilhe esta Página