graph - 如何在散景中为networkx图添加边缘标签(交互式或永久标签)?
问题描述
我想使用散景为networkx图中的边添加标签。我怎样才能做到这一点?
解决方案
这个问题类似于如何在散景中的networkx图的节点上添加永久名称标签(不是交互式标签)?但差异足以保证它自己的答复。正如在另一个问题中所讨论的,这目前是一项可能比它应该完成的任务更难。我真的鼓励你打开一个GitHub 问题来开始讨论如何为用户改进它。
这是完整的示例。
import networkx as nx
from bokeh.io import output_file, show
from bokeh.models import CustomJSTransform, LabelSet
from bokeh.models.graphs import from_networkx
from bokeh.plotting import figure
G=nx.nx.barbell_graph(3,2)
p = figure(x_range=(-3,3), y_range=(-3,3))
p.grid.grid_line_color = None
r = from_networkx(G, nx.spring_layout, scale=3, center=(0,0))
r.node_renderer.glyph.size=15
r.edge_renderer.glyph.line_alpha=0.2
p.renderers.append(r)
这部分都是相当标准的。要将标签放在边缘上,我们必须定义转换以从布局提供程序中提取开始和结束坐标。此代码只是平均坐标以将标签放在每个边缘的中心(由start-end
节点编号标记):
from bokeh.transform import transform
# add the labels to the edge renderer data source
source = r.edge_renderer.data_source
source.data['names'] = ["%d-%d" % (x, y) for (x,y) in zip(source.data['start'], source.data['end'])]
# create a transform that can extract and average the actual x,y positions
code = """
var result = new Float64Array(xs.length)
coords = provider.get_edge_coordinates(source)[%s]
for (var i = 0; i < xs.length; i++) {
result[i] = (coords[i][0] + coords[i][1])/2
}
return result
"""
xcoord = CustomJSTransform(v_func=code % "0", args=dict(provider=r.layout_provider, source=source))
ycoord = CustomJSTransform(v_func=code % "1", args=dict(provider=r.layout_provider, source=source))
# Use the transforms to supply coords to a LabelSet
labels = LabelSet(x=transform('start', xcoord),
y=transform('start', ycoord),
text='names', text_font_size="12px",
x_offset=5, y_offset=5,
source=source, render_mode='canvas')
p.add_layout(labels)
show(p)
推荐阅读
- c++ - Arduino函数无法编辑数组
- pyspark - Dataproc 主节点和工作节点之间的 Python 版本不同
- continuous-integration - 在 GitLab CI 中使用 Karma 为 Angular 项目运行单元测试的问题
- ruby - 在Ruby中随机更改字符串中的字符
- amazon-web-services - 是否可以在 AWS Lambda 中进行影子启动?
- amazon-web-services - AWS 上传后 S3 不会触发 lambda 函数
- python - 如何使用 PyVISA 发送低级 GPIB 命令?
- flutter - Flutter - 如何打开以前在画廊中创建的文件夹
- angularjs - 爸爸解析返回大 csv 的空数组
- python - 如何忽略正面前瞻(正则表达式)的第一个换行符