0

Is anyone aware of a way to put in an image (vector or raster) in place of a text label for a node or edge in a NetworkX graph visualization?

I prefer a solution that uses the matplotlib plot engine rather than the graphviz, but will take either solution.

Paul
  • 42,322
  • 15
  • 106
  • 123
  • related: http://stackoverflow.com/questions/33190985/substitute-node-labels-with-emoji-using-networkx-in-python – Joel Feb 20 '16 at 04:19
  • Do you want to have the text label show up as an image but also have a circle for the node? – Joel Feb 20 '16 at 04:19

1 Answers1

1

In principle, the below should work. I transform the points into pixel coordinates, and then use figimage to put the image at that point.

import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.image as image

im = image.imread('Lower_case_a.png')

G=nx.fast_gnp_random_graph(2,1)

pos = nx.spring_layout(G)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.patch.set_alpha(0)
ax.axis(xmin=-1,xmax=2,ymin=-1,ymax=2)

for node in G.nodes():
    x,y = pos[node]
    trans_x, trans_y = ax.transData.transform((x,y))
    fig.figimage(im,trans_x,trans_y) #could use custom image for each node

nx.draw_networkx_edges(G,pos)
plt.savefig('tmp.png')

It almost works for me. I get: enter image description here

I think that's because of some weird issue on my computer. When I run the code provided at matplotlib.org to explain transData.transform, it should give meenter image description here, but instead I get enter image description here

So I feel like the offset I'm seeing may be a problem on my machine and I'd like to try another computer. At any rate, let me know if this works for you and hopefully it at least points you in the right direction.

Joel
  • 22,598
  • 6
  • 69
  • 93