I would like to create a set of custom functions in ggplot using multiple variables in a dataframe to calculate the function output. Here's a toy example with slopes and y-intersects stored as 'a' and 'b' in two columns of a data frame. One simple solution I was able to figure out is to manually cycle through the values. output1
library(ggplot2)
# define slope (a) and y intersect (b) of lines
df <- data.frame(a=c(2, 1), b=c(0, -5))
# plot lines with slopes (a) and y intersect (b)
plot <- ggplot() + xlim(-50, 50) +
geom_function(fun = function(x) df$a[1]*x+df$b[1]) +
geom_function(fun = function(x) df$a[2]*x+df$b[2])
print(plot)
If I use a for loop ggplot seems to replace the first function with the second function and I'm not really sure why? output2
library(ggplot2)
# define slope (a) and y intersect (b) of lines
df <- data.frame(a=c(2, 1), b=c(0, -5))
# plot lines with slopes (a) and y intersect (b)
plot <- ggplot() + xlim(-50, 50)
for (i in 1:nrow(df)) {plot <- plot + geom_function(fun = function(x) df$a[i]*x+df$b[i])}
print(plot)
However, neither option is ideal in my eyes, but my intuitive solution clearly gives incorrect results. output3
library(ggplot2)
# define slope (a) and y intersect (b) of lines
df <- data.frame(a=c(2, 1), b=c(0, -5))
# plot lines with slopes (a) and y intersect (b)
plot <- ggplot() + xlim(-50, 50) +
geom_function(fun = function(x) df$a*x+df$b)
print(plot)
Is there no easy way to solve this within ggplot? I don't really want to create a new data frame for discrete x values to retain the option to plot functions instead of points connected by a line.
Clarification
@Allan and @Magnus, I only chose the linear plots as the simplest example, but I would like to plot a custom function f(x) <- s/sqrt(x)/(2*c) for many s and c values. My current work-around has drawbacks (need to enumerate every pair of factors; only plots line connecting discrete data points not smooth function; ...). output4
library(ggplot2)
# define s and c
df <- data.frame(s=c(0.2, 0.5, 0.5), c=c(3, 5, 7))
# plot lines with function f(x) <- s/sqrt(x)/(2*c)
plot <- ggplot() + xlim(0, 50) +
geom_line(data=data.frame(x=1:50, y=df$s[1]/sqrt(1:50/(2*df$c[1]))), aes(x=x, y=y)) +
geom_line(data=data.frame(x=1:50, y=df$s[2]/sqrt(1:50/(2*df$c[2]))), aes(x=x, y=y)) +
geom_line(data=data.frame(x=1:50, y=df$s[3]/sqrt(1:50/(2*df$c[3]))), aes(x=x, y=y))
print(plot)
My 'intuitive' solution of calling the plot without specifying the row item geom_line(data=data.frame(x=1:50, y=df$s/sqrt(1:50/(2*df$c))), aes(x=x, y=y)
doesn't work and would only address part of the problem anyway.