2

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.

ElaSz
  • 107
  • 2
  • 10
  • Could you reformat your code? Indenting by 4 spaces tells stackoverflow it is code. Having '>' tells stackoverflow it is a quote. – Joel Jun 27 '18 at 10:22

3 Answers3

1

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

ElaSz
  • 107
  • 2
  • 10
0

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

import matplotlib 
matplotlib.use('Agg')
import matplotlib.pyplot as plt
  • Thank You jdv, I tried, however nothing changed. Also displaying graph is not so important, crucial for me is saving it. – ElaSz Jun 27 '18 at 17:47
  • @ElaSz I did not provide this answer. I just edited it for clarity. If it does not address your problem you can ignore it or downvote it. –  Jun 27 '18 at 17:48
0

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])
Paul Brodersen
  • 11,221
  • 21
  • 38