Ahdee
Ahdee

Reputation: 4949

Adjust the length of facet_wrap so that each facet reflect number of samples?

I have a plot that looks like below. However as you can see facet 4 only has 1 sample but the vertical size is equal to facet 6 which has 4 samples; this makes the plot look really weird since it becomes really thick. I can't use face_grid (facet_grid( cyl~. , scales = "free", space="free" )) at the moment because because then the labels goes to the side but what I really want is to put the labels on top like with facet_wrap as illustrated below. Is there anyway around this? thanks.

 temp = head ( mtcars ) 
    temp$car = row.names ( temp )
    
    ggplot( temp  , aes(x=car , y=hp, fill=vs   )) +
      geom_bar(stat = 'identity', position = 'stack') +
      theme_bw() +
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
            panel.background = element_blank(), axis.line = element_line(colour = "black"))+
      coord_flip() +
      scale_y_continuous(expand = expansion(mult = c(0, .1))) +
    
      facet_wrap( ~cyl , ncol=1,  scales = "free"  )

enter image description here

Upvotes: 0

Views: 543

Answers (1)

benson23
benson23

Reputation: 19097

Not sure if you want this. If so, you can use facet_col from the package ggforce, which allows you to have facet in a single column and also drop the facet ratio (space argument).

library(tidyverse)
library(ggforce)

temp = head (mtcars) 
temp$car = row.names(temp)

ggplot(temp, aes(x = car , y = hp, fill = vs)) +
  geom_bar(stat = 'identity', position = 'stack') +
  theme_bw() +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  coord_flip() +
  scale_y_continuous(expand = expansion(mult = c(0, .1))) +
  ggforce::facet_col(cyl ~ ., scales = "free", space = "free")

ggforce_facet_col

Upvotes: 2

Related Questions