首页 > 解决方案 > 如何用 ggplot2 (R) 绘制单个置信区间?

问题描述

我正在尝试在单个图表上显示单个置信区间ggplot

当前代码

d1<-rnorm(50,26,6) 
d2<-rnorm(20,19,4)
all_test<-t.test(d1,d2)
mean_CI<-(all_test$conf.int[2]+all_test$conf.int[1])/2

  ggplot(data.frame(x=c()), aes(x)) +
     geom_segment(aes(x = 0, y = all_test$conf.int[1], xend = 0, yend = all_test$conf.int[2]),  arrow = arrow(length = unit(0.02, "npc"),type = "closed",ends="both")) +   
     annotate("point", x = 0, y = mean_CI,size =4)+
     geom_hline(yintercept = 0, linetype = 3, size =1.5) +
     theme_classic()

电流输出 生成的图

当前输出达到预期所需的关键调整:

  1. 用线段替换箭头末端
  2. 更改 x 缩放比例

预期产出

阴谋

其他尝试

评论

我使用的原因ggplot2是因为我创建了第二个ggplot面板,我想将两者结合在同一页面上。

标签: rggplot2

解决方案


使用geom_errorbarandgeom_point这可以像这样实现:

library(ggplot2)

set.seed(42)
d1<-rnorm(50,26,6) 
d2<-rnorm(20,19,4)
all_test<-t.test(d1,d2)
mean_CI<-(all_test$conf.int[2]+all_test$conf.int[1])/2

d <- data.frame(x = 0, 
                y = (all_test$conf.int[2] + all_test$conf.int[1]) / 2,
                ymin = all_test$conf.int[1], 
                ymax = all_test$conf.int[2])

ggplot(d)+ 
  geom_errorbar(aes(x, ymin = ymin, ymax = ymax), width = .1) +
  geom_point(aes(x, y), size = 4)+
  geom_hline(yintercept = 0, linetype = 3, size =1.5) +
  xlim(-.2, .2) +
  theme_classic() +
  theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())


推荐阅读