rmosaic-plot

Error when using Unicode characters to display mathematical operators in a mosaic plot


For example, this works:

library("vcd")
library("vcdExtra")
ppp1 <- Arthritis[,-1]
ppp1 <- ppp1 [,-3]
colnames(ppp1)[1] <- "Dose"
colnames(ppp1)[3] <- "Symptoms"
ppp1$Symptoms <- ordered(ppp1$Symptoms,
levels = c("None", "Some", "Marked"),
labels = c(">2", "1-2", "<1"))
ppp1$Dose <- ordered(ppp1$Dose,
levels = c("Placebo","Treated"),
labels = c("<= 1", ">=2"))
tab1 <- xtabs(~Symptoms+Sex+Dose, data=ppp1)
mosaic(tab1)

But this produces error:

ppp2<- Arthritis[,-1]
ppp2 <- ppp2 [,-3]
colnames(ppp2)[1] <- "Dose"
colnames(ppp2)[3] <- "Symptoms"
ppp2$Symptoms <- ordered(ppp2$Symptoms,
levels = c("None", "Some", "Marked"),
labels = c(">2", "1-2", "<1"))
ppp2$Dose <- ordered(ppp2$Dose,
levels = c("Placebo","Treated"),
labels = c("\u2264 1", "\u2265 2"))
tab2 <- xtabs(~Symptoms+Sex+Dose, data=ppp2)
mosaic(tab2)

Error in grid.Call.graphics(C_downviewport, name$name, strict) :
Viewport 'cell:Symptoms=<1,Sex=Male,Dose=≥ 2' was not found

Any ideas would be much appreciated.


Solution

  • Here is a solution based on the package ggmosaic.
    Important: ggmosaic works fine with the CRAN version of ggplot2 which can be installed using install.packages("ggplot2")

    library(vcd)
    library(vcdExtra)
    
    ppp2 <- Arthritis[,-c(1,4)]
    names(ppp2) <- c("Dose", "Sex", "Symptoms")
    ppp2$Symptoms <- ordered(ppp2$Symptoms, levels=c("None","Some","Marked"),
                                            labels=c(">2", "1-2", "<1"))
    ppp2$Dose <- ordered(ppp2$Dose, levels = c("Placebo","Treated"),
                                    labels = c("<= 1", ">= 2"))
    
    # Reverse the order of levels for Dose and Symptoms
    ppp2$Symptoms <- factor(ppp2$Symptoms, levels=rev(levels(ppp2$Symptoms)), order=T)
    ppp2$Dose <- factor(ppp2$Dose, levels=rev(levels(ppp2$Dose)), order=T)
    
    # Plot mosaic using geom_mosaic from ggmosaic
    library(ggplot2)
    p <- ggplot(data=ppp2) +
      geom_mosaic(aes(x=product(Dose, Sex, Symptoms), fill=Sex), offset=.03) +
      coord_flip() +  xlab("Symptoms; Dose")
    
    # Get grobs
    gt <- ggplot_gtable(ggplot_build(p))
    gt$layout$clip[gt$layout$name == "panel"] <- "off"
    
    # Modify ticks labels on y-axis
    gt$grobs[[3]]$children[[2]]$grobs[[1]]$children[[1]]$label <- 
    c("\u2265 2; <1", "\u2264 1; <1",
      "\u2265 2; 1-2", "\u2264 1; 1-2",
      "\u2265 2; >2", "\u2264 1; >2")
    
    # Plot the mosaic plot
    library(grid)
    grid.draw(gt)
    

    enter image description here