Limit x-axis to current week

Viewed 88

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") 

output for the above data

2 Answers

You can restrict in data itself.

Try with the below code :

data<-dat%>% filter(week < format(Sys.Date(),"%V")) ## filtering based on current week

Plotting :

ggplot(data, 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") +theme(axis.text.x = element_text(angle = 45, vjust = 0.4))

output

Why not add a filter before the plot call for week:

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))

dat %>% 
  filter(week <= 45) %>% # add filter before plot
  ggplot(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") 

enter image description here

Related