ggplot2为几个stat_functions添加一个图例

Xu *_*ang 13 r legend ggplot2

我看到很多关于如何自定义图例的问题,但我甚至无法获得自定义的图例.我想有一个传说解释黑线是二次的,绿线是立方的.

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)

koh*_*ske 17

试试这个:

ggplot(NULL, aes(x=x, colour = g)) +
  stat_function(data = data.frame(x = 1:5, g = factor(1)), fun = myfun1) +
  stat_function(data = data.frame(x = 1:5, g = factor(2)), fun = myfun2) +
  scale_colour_manual(values = c("red", "green"), labels = c("quadratic", "cubic"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述