How to fix graphics being cut off when drawing NetworkX graphs with Matplotlib?

≯℡__Kan透↙ 提交于 2021-02-10 12:57:20

问题


I am using NetworkX and Matplotlib to draw nodes, but the nodes are sometimes being cut off at the edge of the graphic. Is there a setting to increase the margins or prevent them from being cut off?

Image: Nodes being cut off at the edge of the graphic

Example program:

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

adjacency_matrix = np.array([[1,0,0,0,0,0,1,0],[0,1,1,1,1,0,0,0],[0,1,1,0,0,0,0,0],[0,1,0,1,0,0,0,0],
    [0,1,0,0,1,1,0,0],[0,0,0,0,1,1,1,1],[1,0,0,0,0,1,1,0],[0,0,0,0,0,1,0,1]])

nx_graph = nx.from_numpy_matrix(adjacency_matrix)
pos = nx.networkx.kamada_kawai_layout(nx_graph)

nx.draw_networkx_nodes(nx_graph, pos, node_color="#000000", node_size=10000)

nx.draw_networkx_edges(nx_graph, pos, color="#808080", alpha=0.2, width=2.0)

plt.axis('off')
plt.tight_layout()
plt.show()

回答1:


You can scale the axis to avoid that the nodes are cut off

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

adjacency_matrix = np.array([[1,0,0,0,0,0,1,0],[0,1,1,1,1,0,0,0],[0,1,1,0,0,0,0,0],[0,1,0,1,0,0,0,0],
    [0,1,0,0,1,1,0,0],[0,0,0,0,1,1,1,1],[1,0,0,0,0,1,1,0],[0,0,0,0,0,1,0,1]])

nx_graph = nx.from_numpy_matrix(adjacency_matrix)
pos = nx.networkx.kamada_kawai_layout(nx_graph)

nx.draw_networkx_nodes(nx_graph, pos, node_color="#000000", node_size=10000)

nx.draw_networkx_edges(nx_graph, pos, color="#808080", alpha=0.2, width=2.0)

plt.axis('off')
axis = plt.gca()
axis.set_xlim([1.2*x for x in axis.get_xlim()])
axis.set_ylim([1.2*y for y in axis.get_ylim()])
plt.tight_layout()
plt.show()

Depending on your node size you may need to vary the factor (1.2). In your given example this value worked. More information in my answer of a related question.



来源:https://stackoverflow.com/questions/62919781/how-to-fix-graphics-being-cut-off-when-drawing-networkx-graphs-with-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!