How to put text in the top right corner of networkx drawing

Viewed 319

I am drawing a graph and would like to add some text in the top right corner. However I am not sure how to do this. I tried:

import matplotlib.pyplot as plt
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layout

T = nx.balanced_tree(2, 5)


pos = graphviz_layout(T, prog="dot")
nx.draw(T, pos, node_color="y", edge_color='#909090', node_size=200, with_labels=True)

plt.text(0,0,"******************")
plt.show()

to see if I could show any text at all. It does show the asterisks in the bottom left. How do I know the resolution of the diagram so I can work out where the top right is?

1 Answers

You can read in networkx.drawing.nx_pylab.draw_networkx:

draw_networkx(G, pos=None, arrows=None, with_labels=True, **kwds)

Parameters:

ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes.

Then you can create fig, axe = plt.subplots() and pass axe to nx.draw and add title for axe then you can show title for drawing like below:

Set the title with matplotlib.axes.Axes.set_title, which has parameters to set the location of the title, including the use of matplotlib.text arguments. (e.g. x=1 or loc='right').

import matplotlib.pyplot as plt
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layout

T = nx.balanced_tree(2, 5)

fig, axe = plt.subplots(figsize=(12,7))
axe.set_title('Title for NetworkX', loc='right')

pos = graphviz_layout(T, prog="dot")
nx.draw(T, pos, ax = axe, node_color="y", edge_color='#909090', node_size=200, with_labels=True)

plt.show()

Output:

enter image description here

  • When using x=, the title is centered over x on the x-axis; adjust the value for precise positioning.
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 4))
ax1.set_title('Title for NetworkX', loc='right')

ax2.set_title('Title for NetworkX', x=.68)

ax3.set_title('Title for NetworkX', x=1)
fig.tight_layout()

enter image description here

Related