在ggplot2中使用带有stat_function的图例

时间:2013-11-13 09:37:52

标签: r ggplot2

我使用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)

1 个答案:

答案 0 :(得分:37)

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