首页 文章

用ggplot填充R中两条黄土平滑线之间的区域

提问于
浏览
18

我想知道如何在ggplot中填充黄土平滑线之间的区域 .

以下数据框用于图片:

x         y      ymin     ymax grp     ydiff
1   1  3.285614  3.285614 10.14177 min 6.8561586
2   1 10.141773  3.285614 10.14177 max 6.8561586
3   2  5.061879  5.061879 11.24462 min 6.1827368
4   2 11.244615  5.061879 11.24462 max 6.1827368
5   3  8.614408  8.614408 13.45030 min 4.8358931
6   3 13.450301  8.614408 13.45030 max 4.8358931
7   4  6.838143  6.838143 12.34746 min 5.5093150
8   4 12.347458  6.838143 12.34746 max 5.5093150
9   5 10.390673 10.390673 14.55314 min 4.1624713
10  5 14.553144 10.390673 14.55314 max 4.1624713
11  6 12.166937 12.166937 15.65599 min 3.4890495
12  6 15.655987 12.166937 15.65599 max 3.4890495
13  7 13.943202 13.943202 16.75883 min 2.8156277
14  7 16.758830 13.943202 16.75883 max 2.8156277
15  8  5.950011  5.950011 11.79604 min 5.8460259
16  8 11.796037  5.950011 11.79604 max 5.8460259
17  9 17.495731 17.495731 18.96452 min 1.4687841
18  9 18.964515 17.495731 18.96452 max 1.4687841
19 10 15.719466 15.719466 17.86167 min 2.1422059
20 10 17.861672 15.719466 17.86167 max 2.1422059
21 11 19.271996 19.271996 20.06736 min 0.7953623
22 11 20.067358 19.271996 20.06736 max 0.7953623

以下源生成一个具有法线(未平滑)的图形:

ggplot(intdf) + 
    geom_point(aes(x=x, y=y, colour=grp)) +
    geom_ribbon(aes(x=x, ymin=ymin, ymax=ymax), fill="grey", alpha=.4) +
    geom_line(aes(x=x, y=y, colour=grp))

其中x和y是连续数值 . ymin和ymax各自包含位置x处的绿色和红色线的y值 .

Two normal geom_line lines with geom_ribbon filled area

现在我想平滑线条 . 我只需使用以下代码执行此操作:

ggplot(intdf) + 
    stat_smooth(aes(x=x, y=ymin, colour="min"), method="loess", se=FALSE) +
    stat_smooth(aes(x=x, y=ymax, colour="max"), method="loess", se=FALSE)

给出以下情节:

Two smoothed lines without filled region

但我没有设法填补这两行之间的区域 . 我试图拟合黄土模型并使用预测值,但我想我完全使用了错误的预测变量 .

谁能告诉我如何在平滑的线条之间填充区域?

在此先感谢丹尼尔

1 回答

  • 30

    从绘图对象中抓取黄土平滑数据并用于 geom_ribbon 的可能解决方案:

    # create plot object with loess regression lines
    g1 <- ggplot(df) + 
      stat_smooth(aes(x = x, y = ymin, colour = "min"), method = "loess", se = FALSE) +
      stat_smooth(aes(x = x, y = ymax, colour = "max"), method = "loess", se = FALSE)
    g1
    
    # build plot object for rendering 
    gg1 <- ggplot_build(g1)
    
    # extract data for the loess lines from the 'data' slot
    df2 <- data.frame(x = gg1$data[[1]]$x,
                      ymin = gg1$data[[1]]$y,
                      ymax = gg1$data[[2]]$y) 
    
    # use the loess data to add the 'ribbon' to plot 
    g1 +
      geom_ribbon(data = df2, aes(x = x, ymin = ymin, ymax = ymax),
                  fill = "grey", alpha = 0.4)
    

    enter image description here

相关问题