在R中绘制简单的中介图

时间:2017-09-28 09:34:16

标签: r ggplot2 diagram

是否有(最好是简单直接的)方法在R中绘制具有中介系数的简单路径图?

我一直在寻找DiagrammeR套餐,但这看起来有点矫枉过正(说实话,我没弄弄出如何制作情节)。

我知道的其他选项是DiaInkscape,但这些选项需要手动定位,连接路径等。

mediation包有一个plot选项但绘制了自举CI,而我想要实现的是一个简单的路径,其系数如下:

source: http://my.ilstu.edu/~jhkahn/medmod.html

4 个答案:

答案 0 :(得分:3)

虽然@baptiste解决方案可能也有效,但我一直在寻找可发布的格式。

来自plotmat的{​​{1}}函数是让我与我的例子最接近的函数:

path diagram

对于可重现的示例使用:

library(diagram)

答案 1 :(得分:2)

我对ggraph一无所知,但它可能是一条可能的路线。以下5分钟的谷歌搜索引导我:

library(ggraph)
require(igraph)

test <- data.frame(from = c(1,2,3), to=c(2,3,1), coef = letters[1:3])
simple <- graph_from_data_frame(test)
V(simple)$name <- LETTERS[1:3]

ggraph(simple, layout = 'auto') + 
  geom_edge_link(aes(label = coef), 
                 angle_calc = 'along',
                 label_dodge = unit(2.5, 'mm'),
                 arrow = arrow(length = unit(4, 'mm')), 
                 end_cap = circle(3, 'mm')) + 
  geom_node_label(aes(label = name),size = 5) +
  theme_graph()

enter image description here

我不知道如何强制执行几何(如果可能的话),但好处是布局可以自动推广。

答案 2 :(得分:2)

您可以使用“心理”软件包来测试您的审核/调解,它也会给您带来情节。

mediate(Output ~ Independent1 + (Mediator), data =mydata)

答案 3 :(得分:1)

这是使用DiagrammeR构建的中介图的两个版本,以及使用TikZ构建的第三版本。每个都有优点和缺点:

  • DiagrammeR + Graphviz:

    • 优点:易于使用提供的功能创建图表,并提供许多选项来调整节点的设计。
    • 缺点:调整边缘文本的选项很少,输出是htmlwidget对象,可以打印为pdf,但在特定情况下(例如在for循环内)可能需要转换。
  • TikZ

    • 优点:高度可定制,包括边缘文字;易于使用提供的功能生成图
    • 缺点:如果需要HTML输出,它是为LaTeX设计的;语法可能令人困惑
  • DiagrammeR本机语法(仅出于完整性考虑而提供)

    • 专业人士:代码非常易于阅读,为R用户进行编辑
    • 缺点:调整边缘文字的明显方法更少

我已经用函数med_diagram编码了第一和第二个示例,该函数使用glue包来组装相关的graphviz或TikZ代码。该函数需要一个data.frame,该行期望一行包含相关标签和系数的列。对于特定于DiagrammeR的功能,还有一些参数可以调整设计的各个元素。

Diagrammer + Graphviz

med_data <-
  data.frame(
    lab_x   = "Math\\nAbility",
    lab_m   = "Math\\nself-efficacy",
    lab_y   = "Interest in the\\nmath major",
    coef_xm = ".47*",
    coef_my = ".36*",
    coef_xy = "0.33* (.16)"
  )


med_diagram <- function(data, height = .75, width = 2, graph_label = NA, node_text_size = 12, edge_text_size = 12, color = "black", ranksep = .2, minlen = 3){
  
  require(glue)
  require(DiagrammeR)
  
  data$height  <- height   # node height
  data$width   <- width    # node width
  data$color   <- color    # node + edge border color
  data$ranksep <- ranksep  # separation btwn mediator row and x->y row
  data$minlen  <- minlen   # minimum edge length
  
  data$node_text_size  <- node_text_size
  data$edge_text_size  <- edge_text_size
  
  data$graph_label <- ifelse(is.na(graph_label), "", paste0("label = '", graph_label, "'"))

diagram_out <- glue::glue_data(data,
  "digraph flowchart {
      fontname = Helvetica
      <<graph_label>>
      graph [ranksep = <<ranksep>>]

      # node definitions with substituted label text
      node [fontname = Helvetica, shape = rectangle, fixedsize = TRUE, width = <<width>>, height = <<height>>, fontsize = <<node_text_size>>, color = <<color>>]        
        mm [label = '<<lab_m>>']
        xx [label = '<<lab_x>>']
        yy [label = '<<lab_y>>']

      # edge definitions with the node IDs
      edge [minlen = <<minlen>>, fontname = Helvetica, fontsize = <<edge_text_size>>, color = <<color>>]
        mm -> yy [label = '<<coef_my>>'];
        xx -> mm [label = '<<coef_xm>>'];
        xx -> yy [label = '<<coef_xy>>'];
      
      { rank = same; mm }
      { rank = same; xx; yy }
      
      }

      ", .open = "<<", .close = ">>")  


DiagrammeR::grViz(diagram_out)  
}

med_diagram(med_data)

Mediation diagram generated by function

TikZ

TikZ和PGF需要作为LaTeX包加载到序言中。下面的示例代码包括这些软件包和一些其他命令,例如,为图中使用的“ mynode”设置了全局规范。我收到警告,要在自己的序言中加入\pgfplotsset{compat=1.17},但对于其他人则没有必要。请注意,此代码基于此处提供的示例:https://tex.stackexchange.com/a/225940/34597

---
title: "Sample Rmd"
author: "Your name here"
output: pdf_document
header-includes:
  - \usepackage{tikz}
  - \usepackage{pgfplots}
  - \pgfplotsset{compat=1.17}
  - \tikzset{mynode/.style={draw,text width=1in,align=center} }
  - \usetikzlibrary{positioning}
---

```{r, load_packages, include = FALSE}
library(glue)
```
  
```{r, load_function}
med_diagram_tikz <- function(data) {
  glue::glue_data(med_data, 
"
\\begin{figure}
\\begin{center}
\\begin{tikzpicture}[font=\\sffamily]
    \\node[mynode] (m){<<lab_m>>};
    \\node[mynode,below left=of m](x) {<<lab_x>>};
    \\node[mynode,below right=of m](y) {<<lab_y>>};
    \\draw[-latex] (x.north) -- node[auto] {<<coef_xm>>} (m.west);
    \\draw[-latex] (m.east) -- node[auto] {<<coef_my>>} (y.north);
    \\draw[-latex] (x.east) --
            node[below=2mm, align=center] {<<coef_xy>>} (y.west);
\\end{tikzpicture}
\\end{center}
\\end{figure}
", 
.open = "<<", .close = ">>"
)
}
```
  
  
```{r create_diagram, echo = FALSE, results = 'asis'}
med_data <-
  data.frame(
    lab_x   = "Math\\\\Ability",
    lab_m   = "Math\\\\self-efficacy",
    lab_y   = "Interest in the\\\\math major",
    coef_xm = ".47*",
    coef_my = ".36*",
    coef_xy = "0.33* (.16)"
  )

tikz_diagram_out <- med_diagram_tikz(med_data)

# requires chunk header to be set to results = 'asis'
cat("\n", tikz_diagram_out, "\n")

```

Mediation diagram drawn in TikZ

Diagrammer本机语法

此中介图的第三个版本使用R用户更容易理解的语法,但我不喜欢边缘标签文本的位置奇怪(因此,上面有两个替代版本)。

library(DiagrammeR)

# Create a node data frame (ndf)
ndf <- create_node_df(
  n         = 3,
  label     = c( "Math\nself-efficacy","Math\nability", "Interest in\nthe math major"),
  shape     = rep("rectangle", 3),
  style     = "empty",
  fontsize  = 6,
  fixedsize = TRUE,
  height    = .5,
  width     = .75,
  color     = "gray80",
  x         = c(1, 2, 3),
  y         = c(1, 2, 1)
)

# Create an edge data frame (edf)
edf <- create_edge_df(
  from     = c(1, 1, 2),
  to       = c(2, 3, 3),
  label    = c(".47*", ".33* (.16)", ".36*"),
  fontsize = 6,
  minlen   = 1,
  color    = "gray80",
  )

# Create a graph with the ndf and edf
graph <- create_graph(
  nodes_df = ndf,
  edges_df = edf
  )

graph %>%
  render_graph()

Example mediation diagram showing edge label text not lining up properly