[Python] How to add spacing between nodes in networkx

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to make a graph to visualize parts in a product and their type of connection inbetween.

    The labels between the nodes are important, not the labels on the nodes themselves. Sometimes the connection lines are not long enough to fit their label or are intersecting.

    I have seen another SO question but that one is about the labels ON the nodes.

    import pandas as pd
    import networkx as nx
    import matplotlib.pyplot as plt

    G = nx.Graph()

    # add nodes
    nodes = set(df["part_a"]).union(set(df["part_b"]))
    G.add_nodes_from(nodes)

    # add edges
    for _, row in df.iterrows():
    G.add_edge(row["part_a"], row["part_b"], type=row["type_of_connection"], force=row["force"], tool=row["tool"])

    # set positions
    pos = nx.spring_layout(G, k=0.1, scale=2)

    # draw
    plt.figure(figsize=(10, 6))
    nx.draw(G, pos, with_labels=True, node_size=700, node_color="lightblue", edge_color="gray", alpha=0.8)

    # tryin to reduce overlap
    edge_labels = {(row["part_a"], row["part_b"]): row["type_of_connection"] for _, row in df.iterrows()}
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=9, label_pos=0.3)

    plt.title(f"Node Graph of Part {df_product['id'].values[0]}: {df_product['brand'].values[0]} {df_product['model'].values[0]}")
    plt.show()



    However in the following picture you can see that sometimes the connection lines are too short to fit the label, or connection lines are intersecting. What can I do? Tried messing with k value or scale but it does not seem to help

    [​IMG]

    Continue reading...

Compartilhe esta Página