有没有办法在R中制作以值或条形图结尾的流程图

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

我正在尝试制作类似于流程图的东西,以根据我编写的模型可视化结果。鉴于我在下面模拟的数据帧,我正在寻找与此图像类似的内容,理想情况下使用条形图而不是 HD 和 MD 值,但此时我会对某些值感到满意。 Chart

这里是一些生成我使用的数据框的代码:

library(Rmisc)
library(dplyr)

df <- data.frame(
  K = sample(c("Low", "High"), 100, replace = TRUE),
  A = sample(c("Low", "High"), 100, replace = TRUE),
  Q = sample(c("Low", "High"), 100, replace = TRUE),
  HD = runif(100, 0, 1),
  MD = runif(100, 0, 1)
)

df_long <- df %>%
pivot_longer(cols = c("HD", "MD"),
           names_to = "defense",
           values_to = "proportion")

fit <- summarySE(df_long,measurevar = "proportion",
             groupvars = c("defense","K","A","Q"))

我尝试过使用 rpart 和各种其他软件包,但我似乎无法得到这样的东西。

任何帮助将不胜感激。

r graph
1个回答
0
投票

我将分三步解决这个问题。首先,制作你的树形图:

library(igraph)
library(tidygraph)
library(ggraph)
library(patchwork)

tree <- make_tree(15, 2) |>
  as_tbl_graph() |>
  mutate(num = 1:15) |>
  filter(num != 1) |>
  mutate(y = rep(seq(8, 1, length.out = 3), c(2, 4, 8))) |>
  mutate(x = c(3, 11, 1, 5, 9, 13, seq(0, 14, 2))) |>
  mutate(label = paste0("italic(", rep(c("K", "A", "Q"), c(2, 4, 8)))) |>
  mutate(label = paste0(label, c("[High])", "[Low])"))) |>
  ggraph(layout = "manual", x = x, y = y) +
  geom_edge_link() +
  geom_node_circle(aes(r = 0.6), fill = "white") +
  geom_node_text(aes(label = label), parse = TRUE, size = 5) +
  coord_equal(expand = FALSE, clip = "off") +
  theme_graph() +
  theme(plot.margin = margin(3, 3, 0, 3))

现在制作你的条形图:

plots <- fit |>
  group_split(K, A, Q) |>
  lapply(function(d) {
    ggplot(d, aes(defense, proportion, fill = defense)) +
      geom_col(width = 0.5) +
      geom_text(aes(label = round(proportion, 2), y = 0.8)) +
      scale_fill_manual(values = c("navy", "red4"), guide = "none") +
      theme_void() +
      theme(axis.text.x = element_text()) +
      coord_cartesian(ylim = c(0, 1)) +
      scale_x_discrete(expand = c(1, 0.5))
  })

最后,将它们拼接在一起:

tree / 
  patchwork::wrap_plots(plots, ncol = 8) +
  plot_layout(heights = c(9, 2))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.