首页 > 解决方案 > facet_grid ggplot2中每个方面的scale_x_date

问题描述

如何缩放每个构面网格的 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))

标签: rggplot2

解决方案


嗯。这对我来说真的很奇怪。您可以使用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"不起作用。


推荐阅读