Cht*_*ect 4 plot r smoothing ggplot2
我有以下简单的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")
Run Code Online (Sandbox Code Playgroud)
输出如下所示:

为什么置信区间不会沿整条曲线显示?
笔记:
fullrange=TRUE因为它只产生一条直的蓝线而不是当前输出中的锯齿形状.limits=c(-1,1))对于置信区间的前三个区段,范围的顶端至少部分超出界限(边界为[-1,1],而不是轴上略微扩展的范围).ggplot默认行为是不显示任何部分超出范围的对象.你可以通过添加oob=scales::rescale_none到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)
Run Code Online (Sandbox Code Playgroud)
更好的记录,也许更直观的解决方案是简单地使用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))
Run Code Online (Sandbox Code Playgroud)