代码之家  ›  专栏  ›  技术社区  ›  Matt L.

缩放log10转换后移除背景填充(通过geom矩形)

  •  3
  • Matt L.  · 技术社区  · 7 年前

    这是虫子,还是我做错了什么?

    可重复的示例数据: mtcars 数据,但是 cyl 可变因素。这是模拟我的数据的最简单的数据集。

    library(dplyr)
    library(ggplot2)
    mtcars_f <- mtcars %>% 
      mutate(cyl.f = factor(cyl)) 
    

    这在正常的y轴刻度下工作良好。

    mtcars_f %>% 
      ggplot(aes(cyl.f, mpg)) +
      geom_rect(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5) +
      geom_point() 
    

    enter image description here

    问题是:

    mtcars_f %>% 
      ggplot(aes(cyl.f, mpg)) +
      geom_rect(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5) +
      geom_point() +
      scale_y_log10()
    

    enter image description here

    this similarly titled question

    用答案编辑: geom_rect

    rect_df <- 
      data_frame(xmin=-Inf, ymin=17.5, xmax=Inf, ymax=22.5)
    mtcars_f %>% 
      ggplot(aes(cyl.f, mpg)) +
      geom_rect(data = rect_df, aes(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax), inherit.aes = F) +
      geom_point() +
      scale_y_log10() +
      scale_x_discrete()
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Tung    7 年前

    这是一个使用 annotate 直到你发现出了什么问题 geom_rect

    library(dplyr)
    library(ggplot2)
    
    mtcars_f <- mtcars %>% 
      mutate(cyl.f = factor(cyl)) 
    
    mtcars_f %>% 
      ggplot(aes(cyl.f, mpg)) +
      scale_y_log10() +
      scale_x_discrete() +
      annotate(geom = "rect", 
               xmin = -Inf, ymin = 17.5, xmax = Inf, ymax = 22.5,
               fill = "light blue", alpha = 0.8) +
      geom_point() +
      theme_classic(base_size = 12)
    

    reprex package (版本0.2.0.9000)。