繁体   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