无法在ggplot中使用min()和max()设置xlim和ylim

val*_*val 6 r ggplot2

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

为什么 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")
Run Code Online (Sandbox Code Playgroud)

这有效:

    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")
Run Code Online (Sandbox Code Playgroud)

小智 6

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")
Run Code Online (Sandbox Code Playgroud)


Gre*_*gor 5

您不能在ggplot对象中引用列名称(除了在内部aes()以及在公式或函数vars()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))
Run Code Online (Sandbox Code Playgroud)

请参阅?scale_x_continuous并特别?expand_scale了解详细信息。也可以有选择地仅填充每个音阶的顶部或底部,示例中有?expand_scale