Lets say I want to create a histogram with color aes and I have several functions fitted for each of the factor-levels of the column that I use for the color aes.
Sorry for the complicated description, here is an example:
library(ggplot2)
set.seed(1234)
wdata = data.frame(
sex = factor(rep(c("F", "M"), each=200)),
weight = c(rnorm(200, 55), rnorm(200, 58)))
head(wdata)
fun_f <- function(x){dnorm(x, mean = 55)}
fun_m <- function(x){dnorm(x, mean = 58)}
p <- ggplot(wdata, aes(x = weight, color=sex, fill = sex)) +
geom_histogram(aes(color = sex),position = "dodge", bins = 30)+
stat_function(fun=function(x){
fun_m(x)*60
},
geom="line",
color ="blue",
size = 1)+
stat_function(fun=function(x){
fun_f(x)*60
},
color ="red",
geom="line",
size = 1)
p
My goal now is to use the color for wdata[sex=="f"]
for fun_f
instead of color="red"
. Analogously for fun_m
.
Is that possible?