Home > front end >  Get equal width bars and dense x-axis in ggplot barplot
Get equal width bars and dense x-axis in ggplot barplot

Time:10-18

I have the following data & code to produce a barplot (building on barplot

However, since not all class / var_1 combinations are present, some space on the x-axis is lost. I would now like to remove the empty space on the x-axis without making the bars wider(!).

Can someone point me to the right direction?

CodePudding user response:

You can use na.omit to remove unused levels, and then use facet_grid with scales = "free_x" and space = "free_x" to remove space.

ggplot(data=na.omit(tmpdf), aes(x = var_1, y = y_, fill=var_1, width=0.75))  
  geom_col(position=position_dodge(width = 0.90), color="black", size=0.2)  
  facet_grid(~ class, scales = "free_x", space = "free_x", switch = "x")  
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        strip.background = element_blank())

enter image description here

CodePudding user response:

Technically, you could tweak a column chart (geom_col) to the desired effect, like so:

mpdf %>%
  mutate(xpos = c(1.6, 2   .2 * 0:3, 3   .2 * 0:3)) %>%
  ggplot()  
  geom_col(aes(x = xpos, y = y_, fill = var_1))  
  scale_x_continuous(breaks = c(1.6, 2.3   0:1), labels = unique(mpdf$class))

However, the resulting barplot (condensed or not) might be difficult to interpret as long as you want to convey differences between classes. For example, the plot has to be studied carefully to detect that variable D runs against the pattern of increasing values from class 2 to 3.

  • Related