Gregory
Gregory

Reputation: 4269

How to map stat_function aesthetics to data in ggplot2?

I want to add a stat_function layer to a plot with an aesthetic mapped to the state of some variable that identifies a set of parameters. I have manually created the two stat_function lines in the minimal working example below. That's generally what the result should look like.

p <- ggplot(data.frame(x = -1:1), aes(x = x))
p + stat_function(fun = function (x) 0 + 1 * x, linetype = 'dotted') +
  stat_function(fun = function (x) 0.5 + -1 * x, linetype = 'solid')

enter image description here

My best guess at how to accomplish this is

params <- data.frame(
  type = c('true', 'estimate'),
  b = c(0, 0.5),
  m = c(1, -1),
  x = 0
)

linear_function <- function (x, b, m) b + m * x
p + stat_function(data = params,
                  aes(linetype = type, x = x),
                  fun = linear_function,
                  args = list(b = b, m = m))

This form works if I use constants like args = list(b = 0, m = 1), but when I try to get the values for the parameters out of the params data frame it's unable to find those columns. Why is this not working like I expect and what's a solution?

Upvotes: 5

Views: 1101

Answers (1)

merv
merv

Reputation: 76700

Unfortunately, nothing positive to add here; the fact stands: stat_function does not support this functionality.

The alternative is to either use for loops to make layers, as demonstrated in this question, or generate the grid data yourself, which is what was suggested as a closing comment to a feature request discussion about adding this functionality.

Upvotes: 1

Related Questions