facet_grid ggplot2中每个方面的scale_x_date

时间:2018-12-07 04:32:48

标签: r ggplot2

如何缩放每个构面网格的x轴?我尝试了scales = "free",但是由于某种原因,这不适用于密度或直方图。这是我尝试过的。

该图显示了date中的所有日期,而不仅仅是该构面网格的x值。

df <- data.frame(date = as.Date(paste(sample(2000:2010, size = 100, replace = TRUE) - 1, "01", "01", sep = "-")), 
                 fact = sample(c(0,1), size = 100, replace = TRUE))

df <- df %>% mutate(year = format(as.Date(date, format="%Y-%m-%d"),"%Y"))

ggplot(df, aes(x = date, fill = factor(fact))) + 
  geom_histogram(alpha = 0.3, bins = 50) + 
  facet_grid(year ~ ., scales = "free", space="free") + 
  theme_bw() + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

1 个答案:

答案 0 :(得分:1)

嗯。这对我来说似乎很奇怪。您可以使用facet_wrap,使其看起来更像facet_grid

ggplot(df, aes(x = date, fill = factor(fact))) + 
  geom_histogram(alpha = 0.3, binwidth = 1) + 
  facet_wrap(~year, scales = "free", ncol = 1,
             strip.position = "right") + 
  theme_bw() + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

或者您可以切换到水平布局。

ggplot(df, aes(x = date, fill = factor(fact))) + 
geom_histogram(alpha = 0.3, binwidth = 1) + 
facet_grid(~year, scales = "free") + 
theme_bw() + 
theme(axis.text.x = element_text(angle = 90, hjust = 1))

但是...我不知道为什么scales = "free"无法正常工作。