问题
I tried adding a jpg image to one specific node of the graph. There is no error, but the image is not displayed in the node. The node I am attempting to ad an image is "KCT BS".
img=mpimg.imread('kctbs.jpg')
G=nx.Graph()
G.add_node(('KCT BS'),attr_dict={'image':'img'}) #added the image to the node named #KCTBS
G.add_edges_from([("KCT BS","Placements"),("KCT BS","Courses"),("KCT BS","Faculty"),("KCT BS","Students"),("Faculty","Core:21")],length=100)
pos = nx.spring_layout(G, scale=10)
nx.draw(G,with_labels=True,pos=pos,node_size=500, node_color='r')
# G.node.items(0)
G.nodes['KCT BS']['image']=img
回答1:
You can't draw an image as a node in networkx. But you can draw an image over the node on its position by matplotlib:
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('hex.png')
G = nx.Graph()
G.add_node('KCT BS')
G.add_node('WAKA')
pos = nx.spring_layout(G, scale=10)
nx.draw(
G,
with_labels=True,
pos=pos,
node_size=500,
node_color='r'
)
ax = plt.gca()
fig = plt.gcf()
trans = ax.transData.transform
trans2 = fig.transFigure.inverted().transform
imsize = 0.1
(x,y) = pos['KCT BS']
xx,yy = trans((x, y))
xa,ya = trans2((xx, yy))
a = plt.axes([xa-imsize/2.0, ya-imsize/2.0, imsize, imsize])
a.imshow(img)
a.set_aspect('equal')
a.axis('off')
plt.show()
It will draw a normal networkx graph (with circles as nodes) and then draw your picture on top of the existing graph picture (note that if you have transparent picture like mine, you will see the original networkx node under it).
来源:https://stackoverflow.com/questions/58010530/image-added-to-one-node-of-a-networkx-graph-is-not-displayed