簡體   English   中英

ggplot2中每個facet的不同函數曲線

[英]Different function curves for each facet in ggplot2

短:

如何在ggplot2中的每個方面繪制不同的用戶/數據定義曲線?


長:

我想基於分面變量,即使用每個方面的不同曲線,將實際數據的分面散點圖與用戶定義的預測數據曲線疊加在一起。

這是一個玩具示例:

我們有關於紅色或白色女王在兩個地點玩兩年的刺蝟數量的數據,有兩種不同的速率治療方法。 我們預計這些治療方法會以每年0.5或1.5的指數速率改變刺蝟種群。 所以數據看起來像

queen <- as.factor(c(rep("red", 8), rep("white",8)))
site <- as.factor(c(rep(c(rep(1,4), rep(2,4)),2)))
year <- c(rep(c(rep(1,2), rep(2,2)),4))
rate <- rep(c(0.5,1.5),8)
hedgehogs <- c(8,10,6,14,16,9,8,11,11,9,9,10,8,11,11,6)    
toy.data <- data.frame(queen, site, year, rate, hedgehogs)

使用以下內容,按比率制作網站的四個不錯方面:

library("ggplot2")
ggplot(toy.data, aes(year, hedgehogs)) +
  geom_point(aes(colour=queen), size=10) +
  scale_colour_manual(values=c("red", "white")) +
  facet_grid(rate ~ site, labeller= label_both)

在此輸入圖像描述

我想將速率曲線疊加到這些圖上。

我們的預測曲線如下:

predict.hedgehogs <- function(year, rate){
  10*(rate^(year-1))
}

刺蝟數量根據速率的指數和年數乘以起始數(此處為10只刺蝟)預測的數量。

我嘗試過使用stat_function進行各種填充,並在正確的軌道上生成了一些東西但是沒有,

例如:

根據geom_hline添加facet特定數據( 參見下頁

facet.data <- data.frame(rate=c(0.5, 0.5, 1.5, 1.5),
                         site=c(1, 2, 1, 2))

然后繪圖

ggplot(toy.data, aes(year, hedgehogs)) +
  geom_point(aes(colour = queen), size = 10) +
  scale_colour_manual(values = c("red", "white")) +
  facet_grid(rate ~ site, labeller = label_both) +
  stat_function(mapping = aes(x = year, y = predict.hedgehogs(year,rate)),
                fun = predict.hedgehogs,
                args = list(r = facet.data$rate), geom = "line")

在此輸入圖像描述

或者為每個費率單獨調用stat_function (即此策略 ):

ggplot(toy.data, aes(year, hedgehogs)) +
  geom_point(aes(colour=queen), size=10) +
  scale_colour_manual(values=c("red", "white")) +
  facet_grid(rate ~ site, labeller= label_both) +
  stat_function(fun=predict.hedgehogs, args=list(rate=0.5), geom="line", rate==0.5)+
  stat_function(fun=predict.hedgehogs, args=list(rate=1.5), geom="line", rate==1.5)
 Error: `mapping` must be created by `aes()` 

有什么想法嗎?

非常感謝@Roland的評論

如果再加上toy.data預測從功能數據predict.hedgehogs以上:

pred.hogs <- predict.hedgehogs(year, rate)
toy.data <- data.frame(toy.data, pred.hogs)

我們可以繪制:

ggplot(toy.data, aes(year, hedgehogs)) +
  geom_point(aes(colour=queen), size=10) +
  scale_colour_manual(values=c("red", "white")) +
  facet_grid(rate ~ site) +
  geom_smooth(aes(x=year, y=pred.hogs), stat="identity", colour = "black")

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM