-1

In ggplot, how can I add a legend entry for each of the geom_functions so that the color and linetype are displayed (e.g for fun1 a short dotted red line), along with a custom name that I choose?

ggplot(data = data.frame(x = seq(0, 1, by=0.01)), mapping = aes(x=x)) +
  geom_function(fun = fun1, linetype='11', color='red') +
  geom_function(fun = fun2, color='dark green') +
  geom_function(fun = fun3, linetype='dashed', color='blue') 
An Ignorant Wanderer
  • 1,322
  • 1
  • 10
  • 23

1 Answers1

0

You can define them inside aes, here is an example with 3 random functions

Code

ggplot(data = data.frame(x = seq(0, 1, by=0.01)), mapping = aes(x=x)) +
  geom_function(fun = dnorm,aes(col = "fun1"))+
  geom_function(fun = dexp,aes(col = "fun2"))+
  geom_function(fun = sin,aes(col = "fun3"))+
  #Defining the colors
  scale_colour_manual(values = c("red","black","purple"))

Output

enter image description here

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32