1

I have a dataframe i like to plot, but ggplot doesent accept that i put color in AES. Instead of 3 different graphs, i get one graph. I expect 3 different graphs. Can anyone see what i am doing wrong?

 df <- data.frame( xNames= c("lisa", "frank", "johnny"),
                coef_a = c(20,25,30),
                coef_b = c(1,3,5)  )


 ggplot(data=df, aes(color=  xNames)  ) +
 stat_function( fun = function(x) (df$coef_a*x) /(df$coef_b+x), size=1,linetype = 
  "dashed") 
 + xlim(0, 10)

I expect the graph to look something like this:

ggplot(data = df) +
 stat_function( fun = function(x)(20 * x) / (1 + x), size = 1) +
stat_function( fun = function(x)(25 * x) / (3 + x), size = 1) +
 stat_function( fun = function(x)(30 * x) / (5 + x), size = 1) +
 xlim(0, 10) 

3 Answers3

2

The problem is that fun in stat_function takes a single vector variable, and returns a vector of y values for each point on the x axis. It doesn't map to individual groups. There are ways round this - see here and here.

In general, you get far better control by creating a new data frame with your calculated results and plotting them anyway:

fun    <- function(x, a, b) (a * x) / (b + x)
xvals  <- seq(0, 10, 0.1)
yvals  <- mapply(function(a, b) fun(xvals, a, b), a = df$coef_a, b = df$coef_b, SIMPLIFY = F)
yvals  <- do.call(c, yvals)
groups <- rep(df$xNames, each = length(xvals))
df2    <- data.frame(xvals = rep(xvals, 3), yvals, groups)

ggplot(data = df2, aes(xvals, yvals, colour = groups)) +
 geom_line(size = 1, linetype = "dashed")

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
0

If you want to show a different chart for each value in xNames, you would want to use facet_wrap instead of aes(color). color maps each value in a variable to a different color when used within aes. facet_wrap creates a chart for each value in a variable.

df <- data.frame(
  xNames = c("lisa", "frank", "johnny"),
  coef_a = c(20, 25, 30),
  coef_b = c(1, 3, 5)
)

ggplot(data = df) +
  stat_function(
    fun = function(x)
      (df$coef_a * x) / (df$coef_b + x),
    size = 1,
    linetype =
      "dashed"
  ) +
  xlim(0, 10) +
  facet_wrap(~ xNames)
0

Not the usual solution @allan-cameron gave you that but perhaps just to help you see how it plays out with ggplot...

library(ggplot2)
exes <- seq(0, 10, 0.1)
df <- data.frame(exes)
df$lisa <- (20 * df$exes) / (1 + df$exes)
df$frank <- (25 * df$exes) / (3 + df$exes)
df$johnny <- (30 * df$exes) / (5 + df$exes)

ggplot(data = df, aes(x = exes)) +
  geom_line(aes(y = lisa), color = "blue", size = 3) +
  geom_line(aes(y = frank), color = "red", size = 1, linetype = 2) +
  geom_line(aes(y = johnny), color = "darkgreen", linetype = 4)

Chuck P
  • 3,862
  • 3
  • 9
  • 20