在图形上绘制一条水平线,其中`method ="loess"具有最大点

use*_*980 -2 r ggplot2

DF

Date     Score  Team
1/1/2011   3    A
1/2/2011   5    A
1/3/2011   15   A
1/4/2011   39   B
1/5/2011   23   B
1/6/2011  100   B
1/7/2011   4    C
1/8/2011  25    C
1/9/2011   30   C

library(ggplot2)
ggplot(df, aes(Date, Score, group=1)) + geom_point() + geom_smooth(method="loess", se=T, size=1) + facet_wrap(~Team)
Run Code Online (Sandbox Code Playgroud)

我喜欢能够绘制一条水平线,其中method ="loess"达到最大值.有没有人在这里有任何关于如何实现这一目标的意见?

And*_*rie 8

使用构建图ggplot_build(),然后提取数据:

p <- ggplot(df, aes(Date, Score, group=1)) + geom_point() + 
  geom_smooth(method="loess", se=T, size=1)

pp <- ggplot_build(p)
p <- p + geom_hline(yintercept = max(pp$data[[2]]$y), col="red")
p
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


结果ggplot_build是一个清单.第二个元素data是您正在寻找的:

str(pp$data)
List of 2
 $ :'data.frame':   9 obs. of  4 variables:
  ..$ x    : int [1:9] 1 2 3 4 5 6 7 8 9
  ..$ y    : num [1:9] 3 5 15 39 23 100 4 25 30
  ..$ group: int [1:9] 1 1 1 1 1 1 1 1 1
  ..$ PANEL: int [1:9] 1 1 1 1 1 1 1 1 1
 $ :'data.frame':   9 obs. of  7 variables:
  ..$ x    : int [1:9] 1 2 3 4 5 6 7 8 9
  ..$ y    : num [1:9] 1.29 8.67 19.64 24.54 53.86 ...
  ..$ ymin : num [1:9] -103.1 -60.2 -57.3 -52.4 -23 ...
  ..$ ymax : num [1:9] 105.7 77.6 96.5 101.4 130.8 ...
  ..$ se   : num [1:9] 34.8 23 25.6 25.6 25.6 ...
  ..$ group: int [1:9] 1 1 1 1 1 1 1 1 1
  ..$ PANEL: int [1:9] 1 1 1 1 1 1 1 1 1
Run Code Online (Sandbox Code Playgroud)

请注意,此对象是一个列表,其中包含与每个geom对应的数据框.在我的解决方案中,我只是提取最大值yhline通过它绘制一个.


这也适用于多个方面,但您需要做更多工作来提取数据:

p <- ggplot(df, aes(Date, Score, group=1)) + geom_point() + 
  geom_smooth(method="loess", se=T, size=1) + facet_wrap(~Team)

pp <- ggplot_build(p)

library(plyr)
hdat <- ddply(pp$data[[2]], .(PANEL), summarize, hline=max(y))
hdat$Team <- unique(df$Team)[as.numeric(hdat$PANEL)]

p <- p + geom_hline(data=hdat, aes(yintercept = hline), col="red")
p
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @ user1471980看起来很奇怪,你可能不得不自己做自己的工作_some_.除非你愿意付钱给我们......?但是,说真的,如果你没有尽可能少地提供可重复的例子,我们怎么能够知道还有什么问题呢? (2认同)