3

我想在 [-0.25, 0.25] 范围内绘制 y=log(1+x) 和 y=x。到目前为止,这是我的代码-

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")

我不知道如何为这两行添加图例。尝试使用guide_legend,但到目前为止没有任何效果。

有任何想法吗?

4

2 回答 2

4

部分答案:

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"))

尽管在我看来,在绘图之前构建一个 data.frame 会更好。

于 2013-05-28T16:30:46.637 回答
1

这是我解决它的方法。欢迎其他想法。

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())
于 2013-05-28T16:43:53.230 回答