ggplot ggmosic geom_mosaic text for x axis with nested

242 Views Asked by At

I need to change the axis breaks in geom_mosaic. Here is my example:

my_tibble <-
  tibble(a=rep(c("a1","a2"),each=4),
         b=rep(rep(c("b1","b2"),each=2),times=2),
         c=rep(c("c1","c2"),times=4),
         x=seq_along(b)
  )

my_tibble |>
  ggplot() +
  geom_mosaic(aes(x=product(a,b,c),weight=x,fill=a),
              divider=c("vspine","hspine","hspine"))
  

enter image description here

I want only the labels of the outer grouping variable, like this

enter image description here

Can this be achieved with simple function calls in geom_mosaic?

1

There are 1 best solutions below

0
On

I found a solution based on this post: order and fill with 2 different variables geom_bar ggplot2 R

my_tibble |>
  ggplot() +
  geom_mosaic(aes(x=product(a,b,c),weight=x,fill=a),
              divider=c("vspine","hspine","hspine")) +
  labs(x="c") +
  scale_x_productlist(breaks=my_tibble |>
                        group_by(c) |>
                        summarise(pos = sum(x)) |>
                        mutate(pos=cumsum(pos/sum(pos)),
                               lag = lag(pos)) |>
                        replace_na(list(lag=0)) |>
                        rowwise() |>
                        mutate(posx=sum(pos,lag)/2) |> 
                        pull(posx),
                      labels=my_tibble |>
                        pull(c) |>
                        unique())

The code still needs to be cleaned up.