代码之家  ›  专栏  ›  技术社区  ›  conv3d

为facet网格ggplot2中的每个facet缩放x_日期

  •  1
  • conv3d  · 技术社区  · 7 年前

    如何缩放每个镶嵌面网格的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 回复  |  直到 7 年前
        1
  •  1
  •   Erin    7 年前

    呵呵。我觉得很奇怪。你可以使用 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" 不起作用。

    推荐文章