【问题标题】:Using legend with stat_function in ggplot2在 ggplot2 中使用带有 stat_function 的图例
【发布时间】:2013-11-13 09:37:52
【问题描述】:

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-04
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多