Different font faces and sizes within label text entries in ggplot2

后端 未结 3 423
清歌不尽
清歌不尽 2020-12-14 19:52

I am building charts that have two lines in the axis text. The first line contains the group name, the second line contains that group population. I build my axis labels as

3条回答
  •  感情败类
    2020-12-14 20:17

    All,

    Using Triad's cheat this is the closest I was able to get to solution on this one. Let me know if you have any questions:

    library(ggplot2)
    
    spacing <- 0 #We can adjust how much blank space we have beneath the chart here
    
    labels1= paste('Group',c('A','B','C','D'))
    labels2 = rep(paste(rep('\n',spacing),collapse=''),length(labels1))
    labels <- paste(labels1,labels2)
    
    qplot(1:4,1:4, geom="blank") +
     scale_x_continuous(breaks=1:length(labels), labels=labels) + xlab("")+
     opts(plot.margin = unit(c(1, 1, 3, 0.5), "lines"),
          axis.text.x = theme_text(face='bold', size=14))
    
    xseq <- seq(0.15,0.9,length.out=length(labels)) #Assume for now that 0.15 and 0.9 are      constant plot boundaries
    
    sample_df <-  data.frame(group=rep(labels1,each=2),subgroup=rep(c('a','b'),4),pop=sample(1:10,8))
        popLabs <- by(sample_df,sample_df$group,function(subData){
        paste(paste(subData$subgroup,' [n = ', subData$pop,']',sep=''),collapse='\n')
    })
    
    gridText <- paste("grid.text(label='\n",popLabs,"',x=",xseq,',y=0.1)',sep='')
    
    sapply(gridText, function(x){ #Evaluate parsed character string for each element of gridText
      eval(parse(text=x))
    })
    
    grid.gedit("GRID.text", gp=gpar(fontsize=12))
    

    Cheers, Aaron

提交回复
热议问题