Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting multiple functions and adding legends for them in ggplot2

I want to plot y=log(1+x) and y=x in the range [-0.25, 0.25]. Here is my code so far -

library(ggplot2)
log1plusx <- function(x) log(1+x)
self <- function(x) x
ggplot(data.frame(x=c(-0.25, 0.25)), aes(x=x)) + stat_function(fun=log1plusx, color="red") + stat_function(fun=self, color="blue")

I can't figure out how to add the legends for these two lines. Tried using guide_legend, but nothing works so far.

Any ideas?

like image 802
Soumendra Avatar asked Nov 15 '25 22:11

Soumendra


1 Answers

Partial answer:

ggplot(data.frame(x=c(-0.25, 0.25)), aes(x=x)) + 
    geom_path(aes(colour="red"), stat="function", fun=log1plusx)+
    geom_path(aes(colour="blue"), stat="function", fun=self) +
    scale_colour_identity("Function", guide="legend", 
                          labels = c("log1plusx", "self"), 
                          breaks = c("red", "blue"))

Though in my opinion you'll be better off building a data.frame before plotting.

like image 51
baptiste Avatar answered Nov 17 '25 20:11

baptiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!