将 x 轴限制为当前周

Limit x-axis to current week

我尝试将具有多个数字的图的 x 轴限制为当前周。因此,如果我们现在处于第 45 周,则应该显示从 1 到 45 的所有周,而不是从 46 开始的所有周。我无法使用任何 xlim 命令,例如xlim(1,45) returns 错误:

Discrete value supplied to continuous scale.

也许这与变量 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))

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

为什么不在 week 的情节调用之前添加一个 filter:

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

您可以限制数据本身。

尝试使用以下代码:

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