使用 Matplotlib 绘制 NetworkX 图形时如何修复被截断的图形? [英] How to fix graphics being cut off when drawing NetworkX graphs with Matplotlib?

查看:82
本文介绍了使用 Matplotlib 绘制 NetworkX 图形时如何修复被截断的图形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 NetworkX 和 Matplotlib 来绘制节点,但节点有时会在图形边缘被切断.有没有设置可以增加边距或防止被截断?

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?

图像:节点在图形边缘被切断

示例程序:

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()

推荐答案

可以缩放轴以避免节点被切断

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()

根据您的节点大小,您可能需要改变系数 (1.2).在您给出的示例中,此值有效.在我对相关问题的回答中提供了更多信息.

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.

这篇关于使用 Matplotlib 绘制 NetworkX 图形时如何修复被截断的图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆