Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting different custom stat_function on different group of data

Tags:

r

ggplot2

I am trying to associate two different fitted functions to two different groups of data. The data:

> 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

And I fitted those points to the following functions:

# 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
}

I could plot the data and the curves using ggplot2 by doing the following:

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 but I can't associate those functions to the data categories. I would like to link those curves to the categories in df$category so all the aesthetics (e.g. colour) work as if I was using geom_smooth. Programmatically if possible since I'm looking to implement it in a package.

Any idea?

like image 968
IgnacioF Avatar asked Aug 18 '26 13:08

IgnacioF


1 Answers

Does this achieve what you are looking for?

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

like image 154
Z.Lin Avatar answered Aug 20 '26 03:08

Z.Lin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!