1

I am trying to figure out from the documentation how to create a simple graph using the pandas dataframe and the NetworkX package, but I couldn't get the solution. Below the final result I would like.

Desired solution

3
  • 3
    Give more information about data you have in your DataFrame please Commented Feb 9, 2022 at 22:34
  • What is contained in your data frame and what from your image you want to have in the graph? I guess you want to have directed, weighted edges? Do you also want to have the color encoded in your graph via node attributes? Commented Feb 10, 2022 at 8:00
  • Hi I assume I have this dataframe: df = pd.DataFrame({'from': ['A', 'A', 'A', 'C'], 'to': ['B', 'C', 'D', 'D'], 'weight': [10, 5, 4, 1]}). From the graph I would like the directed and weighed edges with the weight label on top of the arrow, as well as the colored nodes. Commented Feb 10, 2022 at 9:01

1 Answer 1

1

This might help:

import pandas as pd
import networkx as nx


df = pd.DataFrame(
    {"from": ["A", "A", "A", "C"], "to": ["B", "C", "D", "D"], "weight": [10, 5, 4, 1]}
)


G = nx.from_pandas_edgelist(
    df, source="from", target="to", edge_attr=["weight"], create_using=nx.DiGraph
)
pos = nx.spring_layout(G)  # node positions

edge_labels = nx.get_edge_attributes(G, "weight") # labels to use for edges

nx.draw(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
Sign up to request clarification or add additional context in comments.

2 Comments

You forgot to pass pos to the first draw call.
Thank you @PaulBrodersen it is very useful, is there also a way to change the thickness of the arrow based on the value of the "weight" and the color of the nodes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.