短的:
您如何在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.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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句