繁体   English   中英

R : 使用 ggplot2 部分显示的置信区间(使用 geom_smooth())

[英]R : confidence interval being partially displayed with ggplot2 (using geom_smooth())

我有以下简单的 R 代码:

disciplines <- c("A","C","B","D","E")
# To stop ggplot from imposing alphabetical ordering on x-axis
disciplines <- factor(disciplines, levels=disciplines, ordered=T)

d1 <- c(0.498, 0.521, 0.332, 0.04, 0.04)
d2 <- c(0.266, 0.202, 0.236, 0.06, 0.06)
d3 <- c(0.983, 0.755, 0.863, 0.803, 0.913)
d4 <- c(0.896, 0.802, 0.960, 0.611, 0.994)

df <- data.frame(disciplines, d1, d2, d3, d4)
df.m <- melt(df)
graph <- ggplot(df.m, aes(group=1,disciplines,value,colour=variable,shape=variable)) +
         geom_point() +
         geom_smooth(stat="smooth", method=loess, level=0.95) +
         scale_x_discrete(name="Disciplines") +
         scale_y_continuous(limits=c(-1,1), name="Measurement")

输出如下所示:在此处输入图片说明

为什么置信区间不显示在整条曲线上?

注意事项:

  1. 我不想让fullrange=TRUE因为这只会在当前输出中产生一条蓝色直线而不是锯齿形。
  2. 我正在将此图与另一个在 (0,-1] 范围内具有负值的图进行比较,这就是为什么 y 轴具有limits=c(-1,1) )

对于置信区间的前三个部分,范围的顶端至少部分超出范围(范围是 [-1, 1],而不是轴上略微扩大的范围)。 ggplot的默认行为是不显示任何部分越界的对象。 您可以通过将oob=scales::rescale_none添加到scale_y_continuous来解决此scale_y_continuous

library(scales)
graph <- ggplot(df.m, aes(group=1,disciplines,value,colour=variable,shape=variable)) +
         geom_point() +
         geom_smooth(stat="smooth", method=loess, level=0.95) +
         scale_x_discrete(name="Disciplines") +
         scale_y_continuous(limits=c(-1,1), name="Measurement", oob=rescale_none)

一个更好的文档,也许更直观的解决方案是简单地使用coord_cartesian

ggplot(df.m, aes(group=1,disciplines,value,colour=variable,shape=variable)) +
         geom_point() +
         geom_smooth(stat="smooth", method=loess, level=0.95) +
         scale_x_discrete(name="Disciplines") +
         coord_cartesian(ylim = c(-1,1))

暂无
暂无

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

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