Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: how to reduce space between narrow width bars, after coord_flip, and panel border

Tags:

r

width

ggplot2

When you have flipped coordinates, how do you reduce the space between bars that are narrow and the panel border? Using the data frame df and the ggplot commands, there is much white space between the bottom bar and the tick marks (and similarly a wide space above the "vendor" bar).

df <- data.frame(x = c("firm", "vendor"), y = c(50, 20))

ggplot(df, aes(x = x, y = y)) + 
  geom_bar(stat = "identity", width = 0.4) + 
  theme_tufte() +  coord_flip() +
  labs(x = "", y = "")

enter image description here

I tried scale_x_discrete with both limits and expand arguments to no avail as well as position = position dodge, likewise with no effect.

This question offers coord_equal to change the aspect ratio, and thereby reduce or eliminate the extra space, but notes that the solution does not work with coord_flip.

like image 962
lawyeR Avatar asked Aug 31 '25 01:08

lawyeR


1 Answers

I think I have found a solution. You can remove width from geom_bar and introduce theme(aspect.ratio = .2), then you can play with the ratio to find the desired width. And unlike coord_equal or coord_fixed is compatible with coord_flip.

ggplot(df, aes(x = x, y = y)) + 
  geom_bar(stat = "identity") + 
  theme_tufte() + theme(aspect.ratio = .2) +
  coord_flip() +
  labs(x = "", y = "")

enter image description here

like image 102
mpalanco Avatar answered Sep 05 '25 02:09

mpalanco