Search code examples
ralignmentsubtitle

R: Histogram subtitle with mtext: how to get tabular alignment in columns?


I have a plot with a multi-line subtitle:

multiline subtitle plot

Current code for the text:

bq1 <- bquote("Raw: "
              ~ mu 
              ~ "=" 
              ~ .(format(round(mean(stepsperday$steps), digits=2), big.mark=","))
              ~ ", " 
              ~ sigma 
              ~ "=" 
              ~ .(format(round(sd(stepsperday$steps), digits=2), big.mark = ","))
              ~ ", median ="
              ~ .(format(median(stepsperday$steps), big.mark = ","))
)

bq2 <- bquote("Imputed: "
              ~ mu 
              ~ "=" 
              ~ .(format(round(mean(stepsperday.imputed$steps), digits=2), big.mark=","))
              ~ ", " 
              ~ sigma 
              ~ "=" 
              ~ .(format(round(sd(stepsperday.imputed$steps), digits=2), big.mark = ",", digits = 6))
              ~ ", median ="
              ~ .(format(median(stepsperday.imputed$steps), big.mark = ","))
)

mytext <- list(bq2, bq1)
mtext(do.call(expression, mytext),side=3,line=0:1, cex=.75)

I would like the 2 lines horizontally aligned on the respective bits of data - the means, sd, median, like they're in a table.

Is there any way to do this?

thanks for any tips,

sff


Solution

  • per the comments, the following is adequate:

    data1 <- "      Raw:"
    data2 <- "Imputed:"
    mytext1 <- list(data2, data1)
    mtext(do.call(expression, mytext1), side=3, line=0:1, adj=c(.23, .23), cex=.75)
    
    bq1 <- bquote("  " ~ mu 
                  ~ "=" 
                  ~ .(format(round(mean(stepsperday$steps), digits=2), big.mark=","))
                  ~ " " 
                  ~ sigma 
                  ~ "=" 
                  ~ .(format(round(sd(stepsperday$steps), digits=2), big.mark = ","))
                  ~ " median ="
                  ~ .(format(median(stepsperday$steps), big.mark = ","))
    )
    
    bq2 <- bquote("   " ~ mu 
                  ~ "=" 
                  ~ .(format(round(mean(stepsperday.imputed$steps), digits=2), big.mark=","))
                  ~ " " 
                  ~ sigma 
                  ~ "=" 
                  ~ .(format(round(sd(stepsperday.imputed$steps), digits=2), big.mark = ",", digits = 6))
                  ~ "   median ="
                  ~ .(format(median(stepsperday.imputed$steps), big.mark = ","))
    )
    
    mytext <- list(bq2, bq1)
    mtext(do.call(expression, mytext), side=3, line=0:1, adj=c(.6, .6), cex=.75)
    

    Which yields output:

    enter image description here