简体   繁体   中英

How to draw a single confidence interval with ggplot2 (R)?

I am trying to display a single confidence interval on a single graph with ggplot .

Current Code

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()

Current Output情节生成

Key adjustments required for the current output to meet expectation:

  1. Replace arrow ends with segments
  2. Change the x scaling

Expected Output

阴谋

Other Attempts

  • geom_errorbar() -> unsuccessful
  • geom_segment() + annotate() -> I think it might not be an elegant solution.

Remark

The reason I am using ggplot2 is because I have created a second ggplot panel and I would like to combine both on the same page.

Using geom_errorbar and geom_point this could be achieved like so:

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM