R图meR水平图

时间:2019-01-09 11:58:00

标签: r diagrammer

我想使用R中的DiagrammeR软件包绘制水平图。但是,我只发现绘制垂直图。知道如何将其翻转90°吗?

library(DiagrammeR)
library(dplyr)

create_graph() %>% 
  add_nodes_from_table(table=n,label_col = task) %>% 
  add_edges_from_table(table=e,from_col = from,to_col = to,from_to_map = label) %>% 
  set_node_attrs(
    node_attr = "shape",
    values = "square"
  ) %>%
  render_graph(layout = "tree")

结果:

enter image description here

dput:

n <- structure(list(task = c("1", "2", "3", "4", "5", "6", "7", "8", 
"A", "B", "C")), .Names = "task", row.names = c(NA, -11L), class = "data.frame")
e <- structure(list(from = c("A", "1", "2", "4", "B", "3", "C", "5"
), to = c("1", "2", "4", "8", "3", "6", "5", "7")), .Names = c("from", 
"to"), row.names = c(NA, -8L), class = "data.frame")

2 个答案:

答案 0 :(得分:0)

我只使用了我的以前的模板来说明替代方案:

grViz("
      digraph Random{
      graph [layout = circo,
      overlap =T,
      outputorder = edgesfirst,
      bgcolor='white',
      splines=line]#controls l type setup
      edge[labelfontname='Arial',fontSize=13,color='red',fontcolor='navy']
      node [shape = box,style='filled',
      fillcolor='indianred4',width=2.5,
      fontSize=20,fontcolor='snow',
      fontname='Arial']#node shape
      a [label = 'A']
      b [label = 'B']
      c [label='D']
      a->b[color='red'] 
      b->c[color='dodgerblue']
      }")

输出: enter image description here

答案 1 :(得分:0)

我发现的唯一方法是在将dot格式传递给grViz之前对其进行处理。在这里,我将默认布局选项替换为dot布局,并通过添加rankdir = LR来翻转它。

DiagrammeR::generate_dot(graph)  %>% 
    gsub(pattern = 'neato',replacement = 'dot',x= .) %>%
    gsub(pattern = "graph \\[",'graph \\[rankdir = LR,\n',x = .)%>%
    grViz

所以就您而言

n <- structure(list(task = c("1", "2", "3", "4", "5", "6", "7", "8", 
                             "A", "B", "C")), .Names = "task", row.names = c(NA, -11L), class = "data.frame")
e <- structure(list(from = c("A", "1", "2", "4", "B", "3", "C", "5"
), to = c("1", "2", "4", "8", "3", "6", "5", "7")), .Names = c("from", 
                                                               "to"), row.names = c(NA, -8L), class = "data.frame")

create_graph() %>% 
    add_nodes_from_table(table=n,label_col = task) %>% 
    add_edges_from_table(table=e,from_col = from,to_col = to,from_to_map = label) %>% 
    set_node_attrs(
        node_attr = "shape",
        values = "square",
    ) %>%
    set_node_attrs(
        node_attr = 'fontcolor',
        values = 'black'
    ) %>% 
    generate_dot() %>% 
    gsub(pattern = 'neato',replacement = 'dot',x= .) %>%
    gsub(pattern = "graph \\[",'graph \\[rankdir = LR,\n',x = .,perl = TRUE) %>% 
    grViz()

enter image description here

请注意,我添加了另一个set_node_attrs,以将字体颜色显式设置为黑色。否则,默认字体颜色为浅灰色。