Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add title to Networkx plot?

I want my code to create a plot with a title. With the code below the plot gets created but no title. Can someone clue me in on what I am doing wrong?

import pandas as pd   
import networkx as nx
from networkx.algorithms import community
import matplotlib.pyplot as plt
from datetime import datetime

...

G = nx.from_pandas_edgelist((df), 'AXIS1', 'AXIS2');
nx.draw(G,with_labels=True)

plt.title('TITLE')
plt.axis('off')
plt.savefig('test.png');
like image 228
Matthew David Jankowski Avatar asked Jul 22 '20 15:07

Matthew David Jankowski


2 Answers

I can only think of some intermediate step triggering a call to plt.show before your call to plt.title (though it doesn't look like that should be the case with the shared code). Try setting the title beforehand, and setting an ax, here's an example:

plt.figure(figsize=(10,5))
ax = plt.gca()
ax.set_title('Random graph')
G = nx.fast_gnp_random_graph(10,0.2)
nx.draw(G,with_labels=True, node_color='lightgreen', ax=ax)
_ = ax.axis('off')

enter image description here

like image 119
yatu Avatar answered Nov 11 '22 20:11

yatu


Probably OP doesn't need this anymore, but for future searchers: the title shows if it's added before the call to nx.draw(), e.g.

plt.figure()  
plt.title(plot_title)
nx.draw(G, node_size=20)
plt.show()
like image 42
Annie Avatar answered Nov 11 '22 21:11

Annie