在ggplot2中使用带有stat_function的图例 [英] Using legend with stat_function in ggplot2
本文介绍了在ggplot2中使用带有stat_function的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 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),color =红色)+
stat_function(fun = MyFun,n = 1000,args = list(p = 3),color =blue)+
stat_function(fun = MyFun,n = 1000,args =列表(p = 2),color =green)+
stat_function(fun = MyFun,n = 1000,args = list(p = 1),color =orange)+
scale_colour_manual values = c(red,blue,green,orange))
print(plt)
解决方案在
aes()中放置 color =
/ code>,然后为特定行提供名称,如图例中所示。图例仅用于 aes()
调用中的美学。 ggplot(my.df,aes(x = x))+
stat_function(fun = MyFun,n = 1000,args = list(p = 10),aes(color =line1))+
stat_function(fun = MyFun,n = 1000,args = list(p = 3),aes(color =line2 ))+
stat_function(fun = MyFun,n = 1000,args = list(p = 2),aes(color =line3))+
stat_function(fun = MyFun,n = 1000 ,args = list(p = 1),aes(color =line4))+
scale_colour_manual(Lgend title,values = c(red,blue,green ))
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)
解决方案 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"))
这篇关于在ggplot2中使用带有stat_function的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文