facet_share from ggpol creates too large margin

Viewed 462

I am getting some problematic margins using facet_share. They are easily reproducible using the function example with some slight modifications to the example.

library(ggplot2)
library(ggpol)
df <- data.frame(age = sample(1:20, 1000, replace = TRUE), 
                 gender = c("M","F"), levels = c("M", "F"))

# Get the count per age and sex
df$count <- 1
df$age = paste(df$age, "some long string that is too long") # Added long labels
df <- aggregate(count ~ gender + age, data = df, length)

# For the horizontally shared axis, if we want to mirror the axes,
# we have to multiply the first panel by -1, and use coord_flip().
df_h <- df 
df_h$count = ifelse(df_h$gender == "F", df_h$count * -1, df_h$count)

p <- ggplot(df_h, aes(x = factor(age), y = count, fill = gender)) + 
  geom_bar(stat = "identity") +
  facet_share(~gender, dir = "h", scales = "free", reverse_num = TRUE) + 
  coord_flip() +
  labs(x = "Age", y = "Count") + 
  theme(legend.position = "bottom")

p

Produces: enter image description here

With a particular focus on the left margin which seems proportionally sized to that of the label text.

My actual labels are significantly larger making the margin even more absurd.

Does anybody have a fix?

1 Answers

The easiest would be create more meaningful and concise labels... Other options include

  • recreate the facet_share look with some more basic ggplot approach.
  • change ggpol::facet_share's behaviour and drawing something like "NULL" rather than NA.
  • Or here a solution to reduce the column width in the ggplotGrob object:
library(ggplot2)
library(ggpol)
library(gtable)
library(grid)

p <- 
ggplot(df_h, aes(x = factor(age), y = count, fill = gender)) + 
  geom_col() +
  coord_flip()+
  facet_share(~ gender, dir = "h", scales = "free", reverse_num = TRUE) +
  labs(x = "Age", y = "Count") + 
  theme(legend.position = "bottom")

gp <- ggplotGrob(p)

#gp$layout #helps you to understand the gtable object 
#gtable_show_layout(gp) #helps you to understand the gtable object 
gp$widths[4] <- unit(0, 'cm') # you can modify this to your liking

grid.newpage()
grid.draw(gp)

Created on 2020-03-06 by the reprex package (v0.3.0)

Related