【发布时间】:2015-04-20 07:34:44
【问题描述】:
短:
如何在 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 (see bottom page here) 添加方面特定数据
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(即this strategy):
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()`
有什么想法吗?
【问题讨论】:
-
见
help("geom_smooth")中的例子。