建立與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
的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
我apoligize不包括在第一個的所有信息帖子。您的解決方案適用於單個圖形。如果你使用facet_wrap(〜Team),你會如何解決這個問題? – user1471980
@ user1471980請不要再這樣做。但我編輯了我的答案。 – Andrie
奇怪的是這適用於一些團隊,而不是其他團隊。我發現它對於一些球隊來說是完美的,我發現有些球隊沒有正確地劃定球隊,有些球隊甚至沒有平局,任何想法可能會發生什麼? – user1471980