我正在使用 NetworkX 和 matplotlib 以 png 图像作为节点绘制图形。这是我的代码:
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 显示图表。但是,当我使用 Pycharm 时,它显示空白的白色图形。通过 plt.savefig() 保存也不起作用。我尝试在 plt.savefig() 中使用 dpi,但没有任何改变。将非常感谢任何线索。
请您参考如下方法:
保存时添加 bbox_inches='tight' 解决了问题:
plt.savefig('save.png',bbox_inches='tight')
这个参数减少了输出图像周围不必要的空白边距。没有它,只能保存整个图形的一部分。
关于如何在 matplotlib 中保存纯图像的有值(value)的讨论在这里: 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
