3

Hi so I was trying to plot a graph using networkx and matplotlib however, my x and y axes are not showing up despite setting axes to 'on' and also by adding x/y limit to the axis.

I tried implementing other people code to see if the axis would be showing but no luck.

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
        [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
         ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
               'D': 0.5714285714285714,
               'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                    for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), 
node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

Some example code from another thread: how to draw directed graphs using networkx in python?

I even tried his/hers code he provided where I can even see from his screenshot that he is able to display the axis but from my end I get nothing.

Here is the output on my end There is no error message.

Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
Onyx
  • 31
  • 1
  • 2

2 Answers2

11

In some previous version of networkx, the ticks and labels were not set off. Now they are - mostly because the numbers on the axes rarely carry any special meaning.

But if they do, you need to turn them on again.

fig, ax = plt.subplots()
nx.draw_networkx_nodes(..., ax=ax)

#...

ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thank you so much it works now. Yes I can understand that is doesn't really mean too much having the number. It is just for my own visualisation especially using pos to determine where to place the nodes. – Onyx Jul 12 '19 at 09:52
5

Quite an old one, but I had problem with the accepted solution. nx.draw_networkx_nodes is not exactly the same as nx.draw (in particular, it doesn't draw the edges by default). But using draw won't display the axis by itself.

Adding plt.limits("on") allows to use draw (and its syntax) with axis.

fig, ax = plt.subplots()
nx.draw(G,...,ax=ax) #notice we call draw, and not draw_networkx_nodes
limits=plt.axis('on') # turns on axis
ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)
Battleman
  • 392
  • 2
  • 12