gpt4 book ai didi

r - 在 ggplot2 中使用带有 stat_function 的图例

转载 作者:行者123 更新时间:2023-12-03 15:14:19 28 4
gpt4 key购买 nike

我正在使用 scale_colour_manual指定图例中可能的键。但是,如果我使用 stat_function绘制自定义函数,图例丢失。

任何想法为什么会发生这种情况?

library(ggplot2)

MyFun <- function(x, p) {
res <- x^(1 / p)
return(res)
}

my.df <-data.frame(x = c(0,1))
plt <- ggplot(my.df, aes(x=x)) +
stat_function(fun = MyFun, n = 1000, args = list(p = 10), colour = "red") +
stat_function(fun = MyFun, n = 1000, args = list(p = 3), colour = "blue") +
stat_function(fun = MyFun, n = 1000, args = list(p = 2), colour = "green") +
stat_function(fun = MyFun, n = 1000, args = list(p = 1), colour = "orange") +
scale_colour_manual(values = c("red", "blue", "green", "orange"))

print(plt)

最佳答案

colour=aes()然后提供特定行的名称,原样应出现在图例中。传奇只为内在美学而生 aes()称呼。

ggplot(my.df, aes(x=x)) +
stat_function(fun = MyFun, n = 1000, args = list(p = 10), aes(colour = "line1")) +
stat_function(fun = MyFun, n = 1000, args = list(p = 3), aes(colour = "line2")) +
stat_function(fun = MyFun, n = 1000, args = list(p = 2), aes(colour = "line3")) +
stat_function(fun = MyFun, n = 1000, args = list(p = 1), aes(colour = "line4")) +
scale_colour_manual("Lgend title", values = c("red", "blue", "green", "orange"))

enter image description here

关于r - 在 ggplot2 中使用带有 stat_function 的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19950219/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com