4

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?

Soumendra
  • 1,174
  • 1
  • 15
  • 28

2 Answers2

5

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.

baptiste
  • 75,767
  • 19
  • 198
  • 294
  • 1
    I like your solution better. Why is it better to build the data.frame before plotting? – Soumendra May 28 '13 at 17:24
  • I tried that for multiple functions and the labels for the colors are just wrong. How can i adjust the ordering there? Does ggplot has any order of colours? – reox Aug 21 '15 at 12:18
  • i guess something's changed since then, i've added the breaks argument to fix the order – baptiste Aug 21 '15 at 20:55
1

Here is how I solved it. Other ideas are welcome.

log1plusx <- function(x) log(1+x)
self <- function(x) x
plot.range1 <- data.frame(x=c(-0.25, 0.25), Functions = factor(1))
plot.range2 <- data.frame(x=c(-0.25, 0.25), Functions = factor(2))

ggplot(NULL, aes(x=x, colour=Functions)) +
  stat_function(data = plot.range1, fun = log1plusx) +
  stat_function(data = plot.range2, fun = self) +
  scale_colour_manual(values = c("red", "green"), labels = c("log(1+x)", "x")) +
  theme(axis.title.y=element_blank())
Soumendra
  • 1,174
  • 1
  • 15
  • 28