添加自定义图表属性

问题描述 投票:0回答:1

我正在尝试向 igraph 对象添加自定义图形属性。我用的是代码

graph = set_graph_attr(graph, "directed", FALSE)
data_json <- d3_igraph(igraph)
write(data_json, "graph.json")

输出显示为

{
  "nodes" [
     {
        "name": "something"
     },
     {
        "name": "something_else"
     }
  ],
  "links": [
      {
         "source": "something",
         "target": "something_else"
      }
   ],
  "attributes": {
      "directed": false
  }
}

添加的属性进入 json 的

attributes
部分,但我真正想要输出的是:

{
  "nodes" [
     {
        "name": "something"
     },
     {
        "name": "something_else"
     }
  ],
  "links": [
      {
         "source": "something",
         "target": "something_else"
      }
   ],
  "attributes": {
  },
  "directed": false
}

新属性添加在 json 的顶层,而不是添加到

attributes
部分。那可能吗?最终计划是添加几个自定义属性,包括具有更复杂结构的元数据。

r igraph
1个回答
0
投票

d3r::d3_igraph()

source
将属性硬编码到第 47 行的 json 自己的部分中。因此,使用该函数似乎不可能做到这一点。然而,这里有一个受源代码启发的函数,它的作用几乎相同:

generate_d3_json <- function(g) {
    d <- igraph::as_data_frame(g, what = "both")
    d$vertices$id <- rownames(d$vertices)

    l <- c(
        list(
            nodes = d$vertices,
            links = setNames(d$edges, c("source", "edges"))
        ),
        igraph::graph_attr(g)
    )

    jsonlite::toJSON(l, auto_unbox = TRUE, pretty = TRUE)
}

这应该以类似的方式起作用。

g <- igraph::make_ring(3) |>
    igraph::set_graph_attr("directed", FALSE)

generate_d3_json(g)

输出:

{
  "nodes": [
    {
      "id": "1"
    },
    {
      "id": "2"
    },
    {
      "id": "3"
    }
  ],
  "links": [
    {
      "source": 1,
      "edges": 2
    },
    {
      "source": 2,
      "edges": 3
    },
    {
      "source": 1,
      "edges": 3
    }
  ],
  "name": "Ring graph",
  "mutual": false,
  "circular": true,
  "directed": false
} 
© www.soinside.com 2019 - 2024. All rights reserved.