Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using legend with stat_function in ggplot2

Tags:

I am using scale_colour_manual to specify the possible keys in the legend. However, if I use stat_function to plot custom function, the legend is missing.

Any ideas why this happen?

library(ggplot2)  MyFun <- function(x, p) {   res <- x^(1 / p)   return(res) }  my.df <-data.frame(x = c(0,1)) plt <- ggplot(my.df, aes(x=x)) +   stat_function(fun = MyFun, n = 1000, args = list(p = 10), colour = "red") +   stat_function(fun = MyFun, n = 1000, args = list(p = 3), colour = "blue") +   stat_function(fun = MyFun, n = 1000, args = list(p = 2), colour = "green") +   stat_function(fun = MyFun, n = 1000, args = list(p = 1), colour = "orange") +   scale_colour_manual(values = c("red", "blue", "green", "orange"))  print(plt) 
like image 434
Andrej Avatar asked Nov 13 '13 09:11

Andrej


People also ask

What does stat_function do in R?

stat_function() computes the following variables: x. x values along a grid. y.

What is Geom function in R?

Geoms. A layer combines data, aesthetic mapping, a geom (geometric object), a stat (statistical transformation), and a position adjustment. Typically, you will create layers using a geom_ function, overriding the default position and stat if needed.

How do I add a curve in ggplot2?

In order to create a normal curve, we create a ggplot base layer that has an x-axis range from -4 to 4 (or whatever range you want!), and assign the x-value aesthetic to this range ( aes(x = x) ). We then add the stat_function option and add dnorm to the function argument to make it a normal curve.

How do I add a function in ggplot2?

Plotting a function is very easy with curve function but we can do it with ggplot2 as well. Since ggplot2 provides a better-looking plot, it is common to use it for plotting instead of other plotting functions. To plot a function, we should specify the function under stat_function in ggplot.


1 Answers

Put colour= inside the aes() and then provide name for particular line as is should appear in legend. Legend is made for aesthetics that are only inside aes() call.

ggplot(my.df, aes(x=x)) +   stat_function(fun = MyFun, n = 1000, args = list(p = 10), aes(colour = "line1")) +   stat_function(fun = MyFun, n = 1000, args = list(p = 3), aes(colour = "line2")) +   stat_function(fun = MyFun, n = 1000, args = list(p = 2), aes(colour = "line3")) +   stat_function(fun = MyFun, n = 1000, args = list(p = 1), aes(colour = "line4")) +   scale_colour_manual("Lgend title", values = c("red", "blue", "green", "orange")) 

enter image description here

like image 77
Didzis Elferts Avatar answered Oct 09 '22 08:10

Didzis Elferts