首页 > 解决方案 > 如何在 R 中制作前后处理图,然后将其添加到布局函数中?

问题描述

我在 RI 的治疗前后图有几个问题需要解决。

如您所见,我不得不调用 Before 变量ABefore,因为该图按字母顺序打印变量,但是,我不知道如何使它变得更好。

最重要的是boxplot和ggplot并没有按照之前指定的布局打印出来,不知道为什么。

您有任何可能有效的解决方案吗?

这是代码

if(!require(ggpubr)){install.packages("ggpubr")
  library(ggpubr)}
if(!require(tidyr)){install.packages("tidyr")
  library(tidyr)}
if(!require(magrittr)){install.packages("magrittr")
  library(magrittr)}

ABefore <- c(7,13,4,0,9,5,7,1,8,13,2,13)
After <- c(1,7,6,0,6,2,2,1,8,7,4,4)
Ind <- c(1,2,3,4,5,6,7,8,9,10,11,12)
aggrs <- data.frame(Ind,ABefore,After)

layout(matrix(c(1,2)),heights=c(1,1.5))
layout.show(2)
boxplot(Before+After, horizontal = TRUE, col = "blue", main = "Agressivity Before-After")
aggrs %>%
  gather('stage', 'value', ABefore, After)  %>%
  ggplot(aes(x = stage, y = value, group = Ind)) +
  theme_classic()+
  geom_line(linetype = 2) + 
  geom_point(colour = "red") ```

标签: rggplot2layout

解决方案


ggplot 自动将字符变量更改为按字母顺序排列的因子。要覆盖这一点,您可以手动将字符变量设置为具有正确级别顺序的因子。

这将是一个 ggplot 解决方案

Before <- c(7,13,4,0,9,5,7,1,8,13,2,13)
After <- c(1,7,6,0,6,2,2,1,8,7,4,4)
Ind <- c(1,2,3,4,5,6,7,8,9,10,11,12)
aggrs <- data.frame(Ind,Before,After)


aggrs %>%
  gather('stage', 'value', Before, After)  %>%
  mutate(stage  = factor(stage, levels = c("Before", "After"))) %>%
  ggplot(aes(x = stage, y = value, group = Ind)) +
  theme_classic()+
  geom_line(linetype = 2) + 
  geom_point(colour = "red")

制作 ggplot 箱线图

aggrs %>%
  gather('stage', 'value', Before, After)  %>%
  mutate(stage  = factor(stage, levels = c("Before", "After"))) %>%
  ggplot(aes(x = stage, y = value)) +
  theme_classic() +
  geom_boxplot()

将两者结合起来(如果你想要的话)

aggrs %>%
  gather('stage', 'value', Before, After)  %>%
  mutate(stage  = factor(stage, levels = c("Before", "After"))) %>%
  ggplot() +
  theme_classic()+
  geom_line(aes(x = stage, y = value, group = Ind), linetype = 2) + 
  geom_point(aes(x = stage, y = value, group = Ind), colour = "red") +
  geom_boxplot(aes(x = stage, y = value), alpha = .4)

推荐阅读