在ggplot2中绘制多个函数并为它们添加图例 [英] Plotting multiple functions and adding legends for them in ggplot2
问题描述
我想在[-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)
I无法弄清楚如何添加这两行的图例。
有什么想法?
部分回答:
pre $ g $ p $ ggplot(data.frame(x = c(-0.25,0.25)),aes(x = x))+
geom_path(aes(color =red),stat =function,fun = log1plusx)+
geom_path(aes(color =blue),stat =function ,fun = self)+
scale_colour_identity(Function,guide =legend,
labels = c(log1plusx,self),
breaks = c(red ),blue))
尽管在我看来,建立数据会更好。在绘图之前。
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?
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.
这篇关于在ggplot2中绘制多个函数并为它们添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!