Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

r - Using legend with stat_function in ggplot2

I am using scale_colour_manual to specify the possible keys in the legend. However, if I use stat_function to plot custom function, the legend is missing.

Any ideas why this happen?

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Put colour= inside the aes() and then provide name for particular line as is should appear in legend. Legend is made for aesthetics that are only inside aes() call.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...