Home > Blockchain >  How to customize the reserved width for each level of a categorical variable on x-axis [ggplot2]
How to customize the reserved width for each level of a categorical variable on x-axis [ggplot2]

Time:07-30

Now I use the following codes to make a figure:


library(tidyverse)

df_simu <- tibble(
  Var1 = c("A", "B", "B", "B", "B", "C", "C", "C", "C"),
  Var2 = c("P", "W", "X", "Y", "Z", "W", "X", "Y", "Z"),
  value = c(5, 10, 6, 4.5, 3, 5, 5, 4, 2.4)
)

ggplot(df_simu, aes(x=Var1, y=value, fill=Var2, group=Var2)) 
  geom_col(position=position_dodge2(preserve = "single", padding=0))

The resulting figure is
enter image description here

What I should do to reduce (or customize) the reserved space for A, i.e., remove the "black" areas in the following figure?
enter image description here

Thanks in advance!

CodePudding user response:

AFAIK there is no easy option to achieve that. But if a hacky solution is an option for you then you could achieve your desired result with the good old "facets that don't look like facets trick". This time with some additional support from the ggh4x package to get the axis ticks right.

Basically this involves to use facet_grid which via the space argument makes it possible to get rid of the the empty space. To this end facet by Var1 and map Var2 on x. The rest is styling to get rid of the facet look and the axis labels (which now show categories of Var2). Moreover, to place the axis ticks at the right positions I first convert Var2 to a numeric which allows to use a continuous scale and use ggh4x::facetted_pos_scales which allows to specify the scale and ticks separately for each facet:

library(ggplot2)
library(ggh4x)

df_simu <- data.frame(
  Var1 = c("A", "B", "B", "B", "B", "C", "C", "C", "C"),
  Var2 = c("P", "W", "X", "Y", "Z", "W", "X", "Y", "Z"),
  value = c(5, 10, 6, 4.5, 3, 5, 5, 4, 2.4)
)

ggplot(df_simu, aes(x = as.numeric(factor(Var2)), y = value, fill = Var2))  
  geom_col(width = 1)  
  facet_grid(. ~ Var1, scales = "free_x", space = "free_x", switch = "x")  
  ggh4x::facetted_pos_scales(
    list(
      scale_x_continuous(breaks = 1, expand = c(0, .3)),
      scale_x_continuous(breaks = 3.5, expand = c(0, .3)),
      scale_x_continuous(breaks = 3.5, expand = c(0, .3))
    )
  )  
  theme(axis.text.x = element_blank(), strip.background.x = element_blank(), 
        panel.spacing.x = unit(0, "pt"), strip.placement = "outside")

  • Related