Reputation: 1190
I need to figure out how to adjust the width of a plot for based on a a specific variable without having the change the scales = "free"
parameter of facet_wrap
function. I tried using the a case_when
that adjusts the width of the bar based on the variable, but I get an error.
below is reproducible example that shows the issue I'm having.
library(tidyverse)
set.seed(1)
data.frame(date = rep(seq.Date(Sys.Date()
, by = "day", length.out = 10), 3)
,Time = rep(c("AM","PM"), each = 30)
,office = rep(LETTERS[1:3], 2)
,n = sample(c(50:100),60, replace = TRUE)) %>%
add_row(date = Sys.Date(), Time = "AM", office = "Z", n = 80) %>%
ggplot(aes(x = date, y = n, group = office)) +
geom_bar(stat = 'identity', position = 'stack'
,width = .7, show.legend = FALSE, alpha =.75) +
facet_wrap(vars(office, Time), ncol = 2, labeller = "label_both",
scales = "free")
Upvotes: 1
Views: 1266
Reputation: 13803
If you don't specifically require use of facet_wrap()
, you should use facet_grid()
, which contains a very useful argument: space
. Whereas scales
allows the scale of each plot to resize according to "empty" data, space
sort of does the same thing, but allows you to keep the same overall width of the bar constant.
data.frame(date = rep(seq.Date(Sys.Date()
, by = "day", length.out = 10), 3)
,Time = rep(c("AM","PM"), each = 30)
,office = rep(LETTERS[1:3], 2)
,n = sample(c(50:100),60, replace = TRUE)) %>%
add_row(date = Sys.Date(), Time = "AM", office = "Z", n = 80) %>%
ggplot(aes(x = date, y = n, group = office)) +
geom_bar(stat = 'identity', position = 'stack'
,width = .7, show.legend = FALSE, alpha =.75) +
facet_grid(office ~ Time, labeller = "label_both",
scales = "free", space='free')
I do wish facet_wrap()
had space
as an argument, but alas, that is not the case at this time. If you need to have the facets all in one row or column, you can use facet_row()
or facet_col()
from the ggforce
package. They allow the use of the space
argument, but you are limited to only one row or column (not wrapping).
Upvotes: 2