2
votes

I am using NetworkX and matplotlib to draw graph with png images as nodes. Here is my code:

import networkx as nx 
import matplotlib.pyplot as plt 
G = nx.DiGraph()

#DRAWING EDGES ON AXIS 
G.add_edges_from(([1,2],[3,4],[5,6],[7,8]))
pos = nx.circular_layout(G)
fig = plt.figure(figsize=(20, 20)) 
ax = plt.axes([0, 0, 15, 15])
ax.set_aspect('equal') 
nx.draw_networkx_edges(G, pos, ax=ax, arrows=True)

#TRANSFORMING COORDINATES 
trans = ax.transData.transform 
trans2 = fig.transFigure.inverted().transform 

#PUTTING IMAGE INSTEAD OF NODES 
size = 0.2 
p2 = size / 2.0 

for n in G:
   xx, yy = trans(pos[n]) 
   xa, ya = trans2((xx, yy)) 
   a = plt.axes([xa - p2, ya - p2, size, size])
   a.set_aspect('equal')
   a.imshow(image, aspect='auto')
   a.axis('off')

plt.savefig('save.png') 
plt.show()

Jupyter notebook displays graph. However, when I use Pycharm it shows blank white figure. Saving by plt.savefig() also do not works. I tried to play with dpi in plt.savefig() but doesn't change anything. Will be very grateful for any clues.

3
Could you reformat your code? Indenting by 4 spaces tells stackoverflow it is code. Having '>' tells stackoverflow it is a quote.Joel

3 Answers

1
votes

Adding bbox_inches='tight' while saving solved the problem:

plt.savefig('save.png',bbox_inches='tight')

This argument cuts unnecessary whitespace margins around output image. Without it only some part of whole figure is saved.

Valuable discussion about how to save pure image in matplotlib is here: scipy: savefig without frames, axes, only content

You can find the bbox of the image inside the axis (using get_window_extent), and use the bbox_inches parameter to save only that portion of the image

0
votes

I've been similar situation before. Can you please try this:

import matplotlib 
matplotlib.use('Agg')
import matplotlib.pyplot as plt
0
votes

plt.axes expects a rectangle with coordinates expressed as a fraction of the figure canvas. Given figsize=(20,20),

ax = plt.axes([0, 0, 15, 15])

should really be

ax = plt.axes([0, 0, 0.75, 0.75])