[英]How do I write a function for a plot in ggplot2 using correctly aes?
I looked through many answers, but still have problems programming a function for a plot in ggplot2. 我浏览了许多答案,但在ggplot2中为绘图编程功能时仍然遇到问题。 Here is a sample dataset:
这是一个示例数据集:
d<-data.frame(replicate(2,sample(0:9,1000,rep=TRUE)))
colnames(d)<-c("fertilizer","yield")
Now I write the following function - I only want to give x and y to the function: 现在,我编写以下函数-我只想给函数x和y:
test <- function(explanatory,response)
{
plot<- ggplot(d, aes(x =explanatory, y=response)) +
geom_point()+
ggtitle("Correlation between Fertilizer and Yield") +
theme(plot.title = element_text(size = 10, face = "bold"))+
geom_smooth(method=lm, se=FALSE) +
annotate("text", x=800, y=20, size=5,label= cor6)
plot
}
When I call this function with this, 当我用这个调用这个函数时,
test("fertilizer","yield")
I get a graph without any scatter points like this: 我得到一个没有任何散点的图形,如下所示:
Could anybody help me? 有人可以帮我吗? I really want to learn to write functions in R.
我真的很想学习用R编写函数。
Use aes_string
instead of aes
. 使用
aes_string
而不是aes
。 It should work. 它应该工作。 Worked for me :)
为我工作:)
Note: Remove the quotes around your arguments in the function definition. 注意:删除函数定义中参数周围的引号。 Also your cor6 should be in quotes.
另外,您的cor6应该用引号引起来。 See below
见下文
test <- function(explanatory,response)
{
plot<- ggplot(d, aes_string(x =explanatory, y=response)) +
geom_point()+
ggtitle("Correlation between Fertilizer and Yield") +
theme(plot.title = element_text(size = 10, face = "bold"))+
geom_smooth(method=lm, se=FALSE) +
annotate("text", x=800, y=20, size=5,label= "cor6")
plot
}
If you use enquo
and !!
如果您使用
enquo
和!!
, the quotes aren't needed. ,不需要引号。
test <- function(explanatory,response)
{
explanatory <- enquo(explanatory)
response <- enquo(response)
plot <-
ggplot(d, aes(x = !!explanatory, y = !!response)) +
geom_point()+
ggtitle("Correlation between Fertilizer and Yield") +
theme(plot.title = element_text(size = 10, face = "bold"))+
geom_smooth(method=lm, se=FALSE) +
annotate("text", x=800, y=20, size=5,label= 'cor6')
plot
}
test(fertilizer, yield)
Change label= cor6 tp label= "cor6" 更改标签= cor6 tp标签=“ cor6”
Also in: 同样在:
annotate("text", x=800, y=20, size=5,label= cor6)
x, y change the range of your plot, your values go from 1 to 9, remove them or set according to your variables range x,y更改绘图范围,值从1到9,将其删除或根据变量范围进行设置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.