r label plots with fractions

℡╲_俬逩灬. 提交于 2019-12-06 11:00:24

It is not clear what do you want to have. This is an attempt;

  • I use mapply to loop over plots and fractions and generate a list of plots.
  • I create fractions using frac(x,y)
  • I set limits of plots using scale_y_continuous
  • I use gridExtra to arrange plots in the same plot (optional)

Here the complete code:

 ## a generic function that take a fraction ana a  data.frame as inputs
 ## it generate a plot
 plot.frac <- function(dat,frac){
     p <-  ggplot(dat) + 
           geom_line(aes(x=x,y=y, colour="blue")) + 
           geom_line(aes(x=x,y=z, colour="red")) +  
           scale_colour_manual(name="data", values=c("red", "blue"))+
           geom_text(x=dat$x[which.max(dat$y)]-0.05, y = max(dat$y)+4,  
                     label = frac, size=5,parse=TRUE)+
           ## Note the use of limits here to display the annotation 
           scale_y_continuous(limits = c(min(dat$y), max(dat$y)+5))
     p
    }
## create a list of data.frame of mapply    
df.list <- list(df1,df2,df3)
## ggplot2 use plotmath so  for fraction you use frac(x,y)
## here I construct the 2 terms using paste
frac.func <- function(num,den) paste('frac("',num,'","',den,'")',sep='')
num1 <- "line1:23 22 22"
den1 <- "line2: 44 28 32"
num2 <- "line1:23 50 22"
den2 <- "line2: 44 50 32"
num3 <- "line1:23 80 22"
den3 <- "line2: 44 80 32"
## create a list of fractions for mapply

frac.list <- list(frac.func(num1,den1),
              frac.func(num2,den2),
              frac.func(num3,den3))
frac.list <- list(frac,frac,frac)
## use mapply to call the plot over the 2 lists of data.frame and fractions
ll <- mapply(plot.frac,df.list,frac.list,SIMPLIFY=FALSE)
library(gridExtra)
do.call(grid.arrange,ll)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!