[R] ggplot inside of the function
Eric Berger
er|cjberger @end|ng |rom gm@||@com
Mon Nov 25 11:22:17 CET 2019
Hi Mayooran,
If you define the following function
f <- function(m,v) { sprintf("Norm(mu=%.1f, var=%.1f)",m,v) }
Then you can modify the setting of Prob as follows
Prob <- plyr::rename(Prob_df,
c("p_1"=f(mu1,var1),"p_2"=f(mu2,var2),"p_3"=f(mu3,var3)))
The lesson here is that wherever you set a variable to a string, as in
"p_1"="Norm(mu=mu1,var=var1)",
you can create the string dynamically using the function sprintf(),
which returns a string.
Best,
Eric
On Mon, Nov 25, 2019 at 3:54 AM Thevaraja, Mayooran
<M.Thevaraja using massey.ac.nz> wrote:
>
> Hello Folks
> I am working some R package development. When I was using ggplot inside of the function, I need to get the output graph's legend must be corresponding to the input parameters numerical value (need to be automatically changed when we input different parameters). Therefore anyone has any ideas? Here, I have given below a simple example. I need to get my output graph's legend should be Norm(mu=0.2, var=0.8),...
>
>
> example <- function(mu1,mu2,mu3,var1,var2,var3){
> x <- seq(-3,3, by=0.01)
> p_1 <- dnorm(x,mu1,var1)
> p_2 <- dnorm(x,mu2,var2)
> p_3 <- dnorm(x,mu3,var3)
> Prob_df <- data.frame(x,p_1,p_2,p_3)
> Prob <- plyr::rename(Prob_df, c("p_1"="Norm(mu=mu1, var=var1)","p_2"="Norm(mu=mu2, var=var2)","p_3"="Norm(mu=mu3, var=var3)"))
> melten.Prob <- reshape2::melt(Prob, id = "x", variable.name = "Methods", value.name = "Prob")
> ggplot2::ggplot(melten.Prob)+
> ggplot2::geom_point(ggplot2::aes(x = x, y = Prob, group= Methods, colour = Methods ))+
> ggplot2::geom_line(ggplot2::aes(x = x, y = Prob, group= Methods, colour = Methods ))
>
> }
>
> mu1 <- 0.2
> mu2 <- 0.5
> mu3 <- 1
> var1 <- 0.8
> var2 <- 1.2
> var3 <- 2.1
> example(mu1,mu2,mu3,var1,var2,var3)
>
>
> Thanks
> Mayooran
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list