如何使用 ggplot2 获得带有连接点和配对 U 测试的完美“前后”图?

B_s*_*sh_ 1 r ggplot2

我的数据如下所示:

mydata <- data.frame(ID = c(1, 2, 3, 5, 6, 7, 9, 11, 12, 13),          #patient ID
                    t1 = c(37, 66, 28, 60, 44, 24, 47, 44, 33, 47),    #evaluation before
                    t4 = c(33, 45, 27, 39, 24, 29, 24, 37, 27, 42),    #evaluation after
                    sexe = c(1, 2, 2, 1, 1, 1, 2, 2, 2, 1))            #subset
Run Code Online (Sandbox Code Playgroud)

我想做一个简单的前后图。

到目前为止,我设法得到了这个: 丑陋的前后情节

有了这个:

library(ggplot2)
ggplot(mydata) + 
  geom_segment(aes(x = 1, xend = 2, y = t1, yend = t4), size=0.6) +
  scale_x_discrete(name = "Intervention", breaks = c("1", "2"), labels = c("T1", "T4"), limits = c(1, 2)) +
  scale_y_continuous(name = "Var") + theme_bw()
Run Code Online (Sandbox Code Playgroud)

我面临多个问题,你能帮我吗...

  • 在每行的开头和结尾添加黑色圆圈?(geom_point()不起作用)
  • 让线条更平滑(看看它们像素化程度如何,尤其是第二个)?
  • 减少图表左侧和右侧的空白?
  • 添加 T1 和 T4 的中位数(红色),链接这些点,将它们与配对曼惠特尼检验进行比较并在图表上打印 p 值?

我不想将我的数据库重新格式化为长格式,我有很多其他变量和时间点(此处未显示)。我读过其他帖子(例如此处),但提供的解决方案对于看似简单的事情来说看起来非常复杂(但我做不到......)。非常感谢您的帮助!

我将随着进展更新图表:)

编辑

我不想将数据库重新格式化为长格式,因为我有很多其他变量和时间点(此处未显示)...

Mag*_*dmo 5

这是我要做的!请随时询问有关此处发生的情况的问题。

library(tidyverse)

mydata <- data.frame(ID = c(1, 2, 3, 5, 6, 7, 9, 11, 12, 13),          #patient ID
                     t1 = c(37, 66, 28, 60, 44, 24, 47, 44, 33, 47),    #evaluation before
                     t4 = c(33, 45, 27, 39, 24, 29, 24, 37, 27, 42),    #evaluation after
                     sexe = c(1, 2, 2, 1, 1, 1, 2, 2, 2, 1))      

pval <- wilcox.test(x = mydata$t1,y = mydata$t4, paired = T,exact = F)$p.value %>% round(2)

df <- mydata %>% 
  pivot_longer(2:3,names_to = "Time") %>% # Pivot into long-format
  mutate(sexe = as.factor(sexe),
         Time = as.factor(Time)) # Make factors 

ggplot(df,aes(Time,value,color = sexe,group = ID)) + 
  geom_point() + 
  geom_line() + 
  stat_summary(inherit.aes = F,aes(Time,value),
    geom = "point", fun = "median", col = "red", 
    size = 3, shape = 24,fill = "red"
  ) +
  annotate("text", x = 1.7, y = 60, label = paste('P-Value is',pval)) + 
  coord_cartesian(xlim = c(1.4,1.6)) +
  theme_bw()
Run Code Online (Sandbox Code Playgroud)

另请注意,除了长格式数据之外,通常还存在一些随时间重复的变量。请参阅此处的示例:

mydata <- data.frame(ID = c(1, 2, 3, 5, 6, 7, 9, 11, 12, 13),          #patient ID
                     t1 = c(37, 66, 28, 60, 44, 24, 47, 44, 33, 47),    #evaluation before
                     t4 = c(33, 45, 27, 39, 24, 29, 24, 37, 27, 42),    #evaluation after
                     sexe = c(1, 2, 2, 1, 1, 1, 2, 2, 2, 1),
                     var1 = c(1:10),
                     var2 = c(1:10),
                     var3 = c(1:10))


df <- mydata %>% 
  pivot_longer(2:3,names_to = "Time") %>% # Pivot into long-format
  mutate(sexe = as.factor(sexe),
         Time = as.factor(Time))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 查看我的编辑。长格式数据可能比您想象的更灵活! (2认同)