【问题标题】:unable to set xlim and ylim using min() and max() in ggplot无法在 ggplot 中使用 min() 和 max() 设置 xlim 和 ylim
【发布时间】:2018-09-26 17:47:33
【问题描述】:

我在这里遗漏了一些重要的东西并且看不到它。

为什么 min 和 max 不能设置轴限制?

mtcars %>%  
  select(mpg, cyl, disp, wt) %>% 
  filter(complete.cases(disp)) %>% 
  ggplot() +
  geom_point(aes(x=mpg, y=disp, colour=cyl), size=3) +
  xlim(min(mpg, na.rm=TRUE),max(mpg, na.rm=TRUE)) +
  ylim(min(disp, na.rm=TRUE),max(disp, na.rm=TRUE)) +
  scale_colour_gradient(low="red",high="green", name = "cyl")

这行得通:

    mtcars %>%  
      select(mpg, cyl, disp, wt) %>% 
      filter(complete.cases(disp)) %>% 
      ggplot() +
      geom_point(aes(x=mpg, y=disp, colour=cyl), size=3) +
#      xlim(min(mpg, na.rm=TRUE),max(mpg, na.rm=TRUE)) +
#      ylim(min(disp, na.rm=TRUE),max(disp, na.rm=TRUE)) +
      scale_colour_gradient(low="red",high="green", name = "cyl")

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您不能在ggplot 对象中引用列名,除非在aes() 内部和facet* 函数的公式中。但是辅助函数 expand_scale 可以帮助您以更可控的方式扩展音阶。

    例如:

    # add 1 unit to the x-scale in each direction
    scale_x_continuous(expand = expand_scale(add = 1))
    # have the scale exactly fit the data, no padding
    scale_x_continuous(expand = expand_scale(0, 0))
    # extend the scale by 10% in each direction
    scale_x_continuous(expand = expand_scale(mult = .1))
    

    详情请参阅?scale_x_continuous,尤其是?expand_scale。也可以选择性地仅填充每个刻度的顶部或底部,?expand_scale 中有示例。

    【讨论】:

      【解决方案2】:

      ggplot 无法以 dplyr 的方式访问列值。

      你需要添加数据:

      mtcars %>%  
        select(mpg, cyl, disp, wt) %>% 
        filter(complete.cases(disp)) %>% 
        ggplot() +
        geom_point(aes(x=mpg, y=disp, colour=cyl), size=3) +
        xlim(min(mtcars$mpg, na.rm=TRUE),max(mtcars$mpg, na.rm=TRUE)) +
        ylim(min(mtcars$disp, na.rm=TRUE),max(mtcars$disp, na.rm=TRUE)) +
        scale_colour_gradient(low="red",high="green", name = "cyl")
      

      【讨论】:

      • 您发布的解决方案不会考虑之前通过 dplyr 管道传递的过滤器。如何引用和使用传递给 ggplot 的数据子集?例如,如果我想使用 xlim 作为 mean(mpg) ± 3*sd(mpg) ?
      猜你喜欢
      • 2021-07-01
      • 2020-11-25
      • 2014-10-02
      • 1970-01-01
      • 2013-03-29
      • 2020-07-18
      • 1970-01-01
      • 2012-06-12
      相关资源
      最近更新 更多