rmosaic-plotr-mosaic

mosaic plot with two variables


This time i am struggling with plotting a mosaic plot. I have 9 town districts and in every district individuals were scored health score 1 or health score 2+3. I want to visualise this in a plot but i can't seem to get it to work.

My dataset:

> dput(THSWP1_23)
structure(list(`Town District` = c(1, 2, 3, 4, 5, 6, 7, 8, 9), 
`health score 1` = c(50, 236, 215, 277, 261, 333, 414, 385, 
358), `Health score 2 and 3` = c(51, 238, 218, 281, 266, 
339, 421, 393, 367)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -9L))

I have tried:

mosaicplot(THSWP1_23, main = "Test") 

which resulted in: Mosaic plot dataset

But the Town districts are part of the boxes and i want to plot a square for health score 1 and health score 2+3 with town district on the x-axis.

then i tried

> count <- table(THSWP1_23$`health score 1`,THSWP1_23$`Health score 2 and 3`)
> mosaicplot(count)

with the result: mosaic plot

I tried again with a different count.

> count <- table(THSWP1_23$`Town District`,THSWP1_23$`health score 1`,THSWP1_23$`Health score 
2 and 3`)
> mosaicplot(count)
> mosaicplot(THSWP1_23$`health score 1`~THSWP1_23$`Health score 2 and 3`,data=THSWP1_23)

with the result: mosaic again

hope somebody can help. Thanks in advance.


Solution

  • Another option could be creating a stacked bar plot or facet bars by first converting your data to longer format using pivot_longer and after that use geom_col like this:

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    THSWP1_23 %>%
      pivot_longer(cols = c(`health score 1`:`Health score 2 and 3`)) %>%
      ggplot(aes(x = name, y = value, fill = factor(`Town District`))) +
      geom_col() 
    

    THSWP1_23 %>%
      pivot_longer(cols = c(`health score 1`:`Health score 2 and 3`)) %>%
      ggplot(aes(x = name, y = value, fill = factor(`Town District`))) +
      geom_col() +
      facet_wrap(~`Town District`)
    

    Created on 2023-03-10 with reprex v2.0.2