You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Julia的GraphPlot绘图中为带颜色的边和节点添加图例?

解决GraphPlot添加图例的方法

GraphPlot的gplot本身没有内置图例参数,但它基于Compose.jl实现绘图,我们可以手动构建图例并与原图组合。以下是修改后的代码,在图的右上角添加所需图例:

using LightGraphs
using GraphPlot
using Colors
using Compose

# 构建空手道图
g = graphfamous("karate")

# 节点颜色配置
membership = [1,1,1,1,1,1,1,1,2,1,1,1,1,1,2,2,1,1,2,1,2,1,2,1,1,1,1,2,1,1,2,1,1,1]
nodecolor = [colorant"lightgrey", colorant"orange"]
nodefillc = nodecolor[membership]

# 边颜色配置
colors = [colorant"lightgray" for i in 1:78]
colors[42] = colorant"orange"

# 绘制原图,获取Compose上下文对象
p = gplot(g, nodefillc=nodefillc, layout=circular_layout, edgestrokec=colors, edgelabel=1:78)

# 构建图例元素集合
legend_elements = []

# 常规节点图例
push!(legend_elements, compose(context(), 
    circle(0, 0, 5mm), 
    fill(colorant"lightgrey"), 
    stroke(colorant"black"),
    text(10mm, 0, "常规节点", hleft, vcenter)
))

# 备用节点图例
push!(legend_elements, compose(context(), 
    circle(0, 0, 5mm), 
    fill(colorant"orange"), 
    stroke(colorant"black"),
    text(10mm, 0, "备用节点", hleft, vcenter)
))

# 常规边图例
push!(legend_elements, compose(context(), 
    line([(0,0), (10mm,0)]), 
    stroke(colorant"lightgray"),
    strokewidth(2mm),
    text(15mm, 0, "常规边", hleft, vcenter)
))

# 备用边图例
push!(legend_elements, compose(context(), 
    line([(0,0), (10mm,0)]), 
    stroke(colorant"orange"),
    strokewidth(2mm),
    text(15mm, 0, "备用边", hleft, vcenter)
))

# 垂直排列图例元素,设置间距
legend = vstack(legend_elements..., spacing=8mm)

# 将图例放置在原图右上角(相对坐标控制位置)
final_plot = compose(context(), 
    p, 
    compose(context(0.75, 0.05, 0.2, 0.4), legend)
)

# 输出为SVG文件或直接显示
draw(SVG("karate_with_legend.svg", 16cm, 16cm), final_plot)
# display(final_plot)

代码说明

  • 借助Compose.jl的基础绘图函数手动构建图例的节点、线条和文字元素。
  • 通过vstack垂直排列图例项,控制元素间距。
  • 用context(x, y, width, height)指定图例的相对位置:0.75和0.05对应原图右上角区域,0.2和0.4是图例的相对宽高,可根据需求调整。
  • 最后将原图与图例组合,完成带图例的绘图。

内容的提问来源于stack exchange,提问作者JKHA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:20:40