Issue
I want to plot a simple graph using networkx. There are two nodes with labels Python and Programming in each. The code and graph are as follows:
import networkx as nx
G = nx.DiGraph()
G.add_node(0)
G.add_node(1)
G.add_edge(0,1)
nx.draw_networkx(G,
pos = {0:(0, 0), 1: (1, 0)},
node_size = [1000, 2000],
node_color = ["red","green"],
node_shape = "s",
)
I am able to get two separate colors red and green in the two nodes respectively, as well as set different labels in each node. However, I also want to get two different shape of nodes. I want to have first node as it is and second node of diamond shape which can be obtained using d
in node_shape
. I tried passing list in the form of ["s","d"]
, as well as dictionary in the form of {0:"s", 1:"d"}
in the node_shape
.
However, both return an error. How can I get nodes of different shapes here? Is it possible using any other libraries like graphviz, how?
In the other step, I'd like to have the labels enclosed within the nodes. So I set the node_size to 0 and used bbox instead as follows.
nx.draw_networkx(G,
pos = {0:(0, 0), 1: (1, 0)},
node_size = 0,
arrows = True,
labels = {0:"Python",1:"Programming"},
bbox = dict(facecolor = "skyblue")
)
I am able to enclose the labels inside bbox, however, the arrow is not hidden, and the facecolor of bbox in both nodes are same. How can I make the facecolors different in this case? What would be the alternative way to approach this?
Solution
I figured out a way to do it using the graphviz package. The limitation of the NetworkX package is that it does not allow the nodes to have different shapes, although the sizes or color could be set differently in the form of lists. Also, if the bounding box (bbox) is used, then its attributes are uniform across nodes.
However, graphviz offers much more flexibility in this context. The shape, size and color of each nodes can be adapted individually. I did it as follows:
import graphviz
G = graphviz.Digraph()
G.node("Python", style = 'filled', color = "red", shape = "box")
G.node("Programming", style = "filled", color = "green", shape = "ellipse")
G.edge("Python","Programming")
G.view()
As a result, I get the plot as shown: It is also possible to customise the graph further, such as position of nodes, edge color, etc.
Answered By - hbstha123
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.