ggplot2为几个stat_functions添加一个图例 [英] ggplot2 add a legend for several stat_functions

查看:239
本文介绍了ggplot2为几个stat_functions添加一个图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多关于如何定制传奇的问题,但我甚至无法获得定制的传奇。我希望有一个传说解释黑线是二次方的,而绿线是立方。

I see a lot of questions regarding how to customize legends, but I can't even get a legend to customize. I would like to have a legend explaining that the black line is quadratic and that the green line is cubic.

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


推荐答案

试试这个:

Try this:

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

这篇关于ggplot2为几个stat_functions添加一个图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆