我看到很多关于如何自定义图例的问题,但我甚至无法获得自定义的图例.我想有一个传说解释黑线是二次的,绿线是立方的.
library(ggplot2)
myfun1 <- function(x) x^2
myfun2 <- function(x) x^3
myplot <- ggplot(data = data.frame(x = 1:5, y= 1:5), aes(x=x, y=y)) +
stat_function(fun = myfun1, color="green") +
stat_function(fun = myfun2, color="black")
Run Code Online (Sandbox Code Playgroud) 我想将一个stat_function图层添加到一个绘图中,其美学映射到某些标识一组参数的变量的状态。我在下面的最小工作示例中手动创建了两个 stat_function 行。这通常是结果的样子。
p <- ggplot(data.frame(x = -1:1), aes(x = x))
p + stat_function(fun = function (x) 0 + 1 * x, linetype = 'dotted') +
stat_function(fun = function (x) 0.5 + -1 * x, linetype = 'solid')
Run Code Online (Sandbox Code Playgroud)
我对如何做到这一点的最佳猜测是
params <- data.frame(
type = c('true', 'estimate'),
b = c(0, 0.5),
m = c(1, -1),
x = 0
)
linear_function <- function (x, b, m) b + m * x
p + stat_function(data = params,
aes(linetype = type, x …Run Code Online (Sandbox Code Playgroud) 我想在 [-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")
Run Code Online (Sandbox Code Playgroud)
我不知道如何为这两行添加图例。尝试使用guide_legend,但到目前为止没有任何效果。
有任何想法吗?