簡體   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