首页 > 解决方案 > Networkx 图:使边缘远离节点

问题描述

我想在 python 中使用 networkx 绘制有向网络图。当使用不同于 1 的 alpha 值时,边缘的起点也在节点内绘制;然而,箭头很好。

如何使边缘远离我的节点?

我在文档中没有找到任何关于它的信息。设置 alpha=1 显然可以解决它,但这不是我想要的。

import math
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt

pos={"x":(1/2, math.sqrt(3/4)), "y":(0,0), "z":(1,0)}

G=nx.DiGraph()
G.add_edge("x", "y")
G.add_edge("x", "z")
nx.draw(G, pos=pos, with_labels=True, node_size=1500, alpha=0.3, arrows=True,
        arrowsize=20, width=2)
plt.title("Direct link")
plt.show()

这就是结果。边缘继续进入“x”节点,这很糟糕。

在此处输入图像描述

标签: pythonnetworkx

解决方案


您可以通过多次绘制节点来解决此问题:

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

pos={"x":(1/2, math.sqrt(3/4)), "y":(0,0), "z":(1,0)}

G=nx.DiGraph()
G.add_edge("x", "y")
G.add_edge("x", "z")
nx.draw_networkx_edges(G, pos=pos, with_labels=True, node_size=1500, alpha=0.3, arrows=True,
        arrowsize=20, width=2)
# draw white circles over the lines
nx.draw_networkx_nodes(G, pos=pos, with_labels=True, node_size=1500, alpha=1, arrows=True,
        arrowsize=20, width=2, node_color='w')
# draw the nodes as desired
nx.draw_networkx_nodes(G, pos=pos, node_size=1500, alpha=.3, arrows=True,
        arrowsize=20, width=2)
nx.draw_networkx_labels(G, pos=pos)
plt.title("Direct link")
plt.axis("off")
plt.show()


推荐阅读