5

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?

Richard Telford
  • 9,558
  • 6
  • 38
  • 51
Gregory
  • 4,147
  • 7
  • 33
  • 44
  • I don't think `args` can be mapped as regular aesthetics, so an ordinary cycle is probably your best bet. – tonytonov Aug 17 '16 at 09:19
  • If that turns out to be true, then I'll have to post another question about how to create a legend for mappings that ggplot doesn't know about. Ugh. – Gregory Aug 17 '16 at 14:54
  • 1
    I once asked a question about `stat_function` and legends, it may prove helpful: http://stackoverflow.com/questions/19219411/stat-function-and-legends-create-plot-with-two-separate-colour-legends-mapped-t – tonytonov Aug 17 '16 at 15:21

1 Answers1

1

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.

merv
  • 67,214
  • 13
  • 180
  • 245