Search code examples
raxis-labelsmosaic

Moving label position in mosaicplot() in R


Given this example mosaicplot in R,

## create example data frame
set.seed(56)
df1 <- data.frame(Category1 = rep(c("Category name", "Longer category name", "Cat name"), times = c(42, 19, 6)), Category2 = sample(c("Low", "Mid", "High"), 67, replace =T, prob = c(0.25, 0.40, 0.35)))

df1

## make a contingency table
table(df1)

## make the mosaic plot
mosaicplot(table(df1), color = 1:3, las = 2, ylab = "Category2", xlab = "Category1", main = "")

How can I move the Category1 labels (edit: category names) upward so that the complete names are visible?


Solution

  • Like @MrFlick, I can also see the labels. Have you changed your plot margins? Here's how to check:

    par("mar")
    [1] 5.1 4.1 4.1 2.1
    

    I've pasted in the default margins (c(bottom, left, top, right)). If yours are smaller, it might not leave room for the labels. To reset them to the defaults (or whatever you want) do par(mar=c(5,4,4,2)+0.1).

    In any case, if you want to move the labels around, here are some examples:

    mosaicplot(table(df1), color = 1:3, las = 1, main = "", xlab="", ylab="")
    mtext(side = 1, "Category1", line = 0.5, col="green")
    mtext(side = 1, "Category1", line = 1, col="blue")
    mtext(side = 1, "Category1", line = 2, col="red")
    mtext(side = 2, "Category2", line = -1, col="purple")
    

    enter image description here

    UPDATE: To remove the axis labels, save the contingency table as an object and then set the dimnames attribute to NA. You can also, of course change or abbreviate the labels this way as well. For example, to remove the Category1 labels:

    ## make a contingency table
    tab1 = table(df1)
    dimnames(tab1)[["Category1"]] = rep(NA, length(unique(df1$Category1)))
    
    ## make the mosaic plot
    mosaicplot(tab1, color = 1:3, las = 2, ylab = "Category2", 
               xlab = "Category1", main = "")
    

    END UPDATE

    You might also like the mosaic function in the vcd package. It's more complicated, but it gives you more control over the details of the plot. mosaic uses lattice rather than base graphics, so all the adjustments to the plot need to be done with lattice or grid, rather than the base graphics functions or parameters:

    library(vcd)
    mosaic(table(df1), color = 1:3, las = 2, ylab = "Category2", 
           xlab = "Category1", main = "", 
           labeling_args = list(offset_varnames = c(left = 2, top=0)),
           gp = gpar(fill = 1:3))
    

    See this vignette for lots of examples.