I try to limit the x-axis of a plot with several figures to the current week. So if we are now in week 45 all weeks from 1 till 45 should be displayed, but not from 46 onwards. I cannot get any xlim command to work e.g. xlim(1,45) returns Error:
Discrete value supplied to continuous scale.
Perhaps this has to do with the fact that the variable week is a factor, but this is necessary for correct plotting (no decimals). Any solutions?
set.seed(1)
dat <- data.frame(object = sample(c("A","B","C","D"),100,replace = TRUE),
week = sample(c(1:52),100,replace = TRUE),
year = sample(c(2016,2017,2018),100,replace = TRUE),
count = sample(c(0:10),100,replace = TRUE))
ggplot(dat, aes(factor(week), count )) +
geom_bar(stat="identity" , aes(fill = factor(year)), position = position_dodge2(width = 0.9, preserve = "single")) +
facet_wrap(~ object, ncol = 2, scales = "free_y") +
labs(x = "Week", y = "Count") +
scale_fill_discrete(name = "Year")


