在不同的数据组上绘制不同的自定义stat_function

时间:2019-03-21 00:43:14

标签: r ggplot2

我正在尝试将两个不同的拟合函数与两个不同的数据组相关联。 数据:

> df <- structure(list(Var1 = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), 
                     value = c(3465, 4348, 5207, 5945, 6365, 3472, 2589, 2412, 2332, 2289),
                     category = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B")),
                .Names = c("Var1", "value", "category"), 
                row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), 
                class = "data.frame")

> df
   Var1 value category
1     1  3465        A
2     2  4348        A
3     3  5207        A
4     4  5945        A
5     5  6365        A
6     1  3472        B
7     2  2589        B
8     3  2412        B
9     4  2332        B
10    5  2289        B

我将这些要点拟合为以下功能:

# Fitted function for category A
> fitA <- function(x){
  K = 3688
  delta = 0.338
  K * x ^ delta
}

# Fitted function for category B
> fitB <- function(x){
  A = 4902
  B = -1.17
  C = 2289
  A * exp(B * x) + C
}

通过执行以下操作,我可以使用ggplot2绘制数据和曲线:

library(ggplot2)
ggplot(df, aes(x = Var1, y = value)) + 
  geom_point(aes(colour = category)) + 
  stat_function(fun = fitA) + 
  stat_function(fun = fitB) 

ggplot2 with geom_point and stat_function 但我无法将这些功能与数据类别相关联。我想将这些曲线链接到df$category中的类别,以便所有美学(例如colour)都像使用geom_smooth一样工作。如果可能的话,请以编程方式进行,因为我正在寻求在程序包中实现它。

有什么主意吗?

1 个答案:

答案 0 :(得分:1)

这能满足您的需求吗?

library(dplyr)

# place colour = category mapping at the top level for all geom layers to inherit
ggplot(df, aes(x = Var1, y = value, colour = category)) + 

  geom_point() + 

  # pass only the relevant subset of data to each stat layer
  stat_function(data = . %>% filter(category == "A"),
                fun = fitA) +
  stat_function(data = . %>% filter(category == "B"),
                fun = fitB) 

plot