2012-12-04 43 views
-2

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) 

我喜歡能夠繪製一條水平線,其中方法=「黃土」擊中最大。有沒有人有任何關於我如何實現這一目標的意見?

回答

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 

enter image description here


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 

注意,這個對象是對應於每個GEOM數據幀的列表。在我的解決方案中,我只需提取最大值y並通過它繪製一個hline


這適用於多個方面也一樣,但你必須做一些更多的工作來提取數據:

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 

enter image description here

+0

我apoligize不包括在第一個的所有信息帖子。您的解決方案適用於單個圖形。如果你使用facet_wrap(〜Team),你會如何解決這個問題? – user1471980

+0

@ user1471980請不要再這樣做。但我編輯了我的答案。 – Andrie

+0

奇怪的是這適用於一些團隊,而不是其他團隊。我發現它對於一些球隊來說是完美的,我發現有些球隊沒有正確地劃定球隊,有些球隊甚至沒有平局,任何想法可能會發生什麼? – user1471980