Display name
Display name

Reputation: 4481

`space = "free"` not eliminating dead space in ggplot facets

library(tidyverse)
library(scales)
dat <- read.table(text = "A B C
                          1   23  234 324
                          2   34  534 12
                          3   56  324 124
                          4   34  234 124
                          5   123 534 654",
                  sep = "", 
                  header = TRUE) %>% 
  gather(key = "variable", value = "value") %>% 
  mutate(ind = as.factor(rep(1:5, 3)))

ggplot(dat, aes(variable, value, fill = ind)) + 
  geom_bar(position = "fill", stat = "identity") +
  scale_y_continuous(labels = scales::percent_format()) + 
  facet_grid(~variable, space = "free") + 
  theme(axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

I expect the space = "free" argument in facet_grid() to eliminate the dead space in each facet below. For example, facet 'A' should not show the space where there's an empty 'B' and empty 'C' column.

How do I eliminate this dead space in all three facets? I only want one column to show per facet and the two other blank columns in the facets should not be pseudo-plotted.

spacefree

Upvotes: 1

Views: 232

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48211

I believe that instead you want just scales = "free", as in facet_grid(~variable, scales = "free"), giving

enter image description here

I believe that is because:

space - If "fixed", the default, all panels have the same size. If "free_y" their height will be proportional to the length of the y scale; if "free_x" their width will be proportional to the length of the x scale; or if "free" both height and width will vary. This setting has no effect unless the appropriate scales also vary.

So, scales = "free" is necessary for space to have an effect, but with scales` alone we already achieve what is needed in this case.

Upvotes: 2

Related Questions