繁体   English   中英

如何用ggplot2(R)绘制单个置信区间?

[英]How to draw a single confidence interval with 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()

当前 Output情节生成

当前 output需要进行关键调整以满足预期:

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

预计 Output

阴谋

其他尝试

  • geom_errorbar() -> 不成功
  • geom_segment() + annotate() -> 我认为这可能不是一个优雅的解决方案。

评论

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

使用geom_errorbargeom_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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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