Plotting multiple functions and adding legends for them in ggplot2

会有一股神秘感。 提交于 2019-12-03 20:13:07

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.

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())
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!