【问题标题】:Possible to turn off clipping only for certain geoms in ggplot2?可以只为ggplot2中的某些geom关闭裁剪吗?
【发布时间】:2020-12-25 14:45:05
【问题描述】:

我有这个样本密度曲线数据(找到here):

library(tidyverse)
z <- rnorm(1000, mean = 0, sd = 1)
dens <- density(z)
data <- tibble(x = dens$x, y = dens$y) %>% 
  mutate(variable = case_when(
    (x >= -2 & x <= 0) ~ "On",
    (x >= 0.2 & x <= 1) ~ "Off",
    TRUE ~ NA_character_))

我使用 ggplot2 绘制这条曲线,并使用 geom_area 绘制突出显示的区域,以及在绘图边界之外使用 geom_text 创建的一些文本,要求我关闭 coord_cartesian 中的剪辑:

ggplot(data, aes(x, y)) + geom_line() +
  geom_area(data = filter(data, variable == 'On'), fill = 'grey') + 
  geom_area(data = filter(data, variable == 'Off'), fill = 'light blue') +
  geom_text(aes(x = 7, y = 0.15, label = "test")) +
  theme(plot.margin = unit(c(1,7,1,1), "lines")) +
  coord_cartesian(xlim = c(-5, 5),
                  # ylim = c(0.1, 0.2),
                  clip = "off")

我现在想做的是放大 0.1 到 0.2 之间的 y 轴。我知道如果我在scale_y_continuousthen this can sometimes remove data which is constraining the view 中使用limits 参数,那么我在coord_cartesian 中使用ylim 参数设置为c(0.1, 0.2)

但是,这会导致密度区域和曲线与绘图边界重叠(因为我已关闭剪裁)。

我现在可以做的是在coord_cartesian 中打开剪辑,但是现在这会删除我需要的绘图边界之外的 geom_text。有什么办法可以解决我的问题吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是一个以非标准方式使用位置缩放的oob 参数的好用例。 scales 包有几个越界功能可以在这里为您服务,特别是oob_squish(),它将越界设置为最近的限制,或者oob_keep(),它保留越界数据,类似于设置坐标范围。

    library(tidyverse)
    #> Warning: package 'ggplot2' was built under R version 4.0.2
    z <- rnorm(1000, mean = 0, sd = 1)
    dens <- density(z)
    data <- tibble(x = dens$x, y = dens$y) %>% 
      mutate(variable = case_when(
        (x >= -2 & x <= 0) ~ "On",
        (x >= 0.2 & x <= 1) ~ "Off",
        TRUE ~ NA_character_))
    
    ggplot(data, aes(x, y)) + geom_line() +
      geom_area(data = filter(data, variable == 'On'), fill = 'grey') + 
      geom_area(data = filter(data, variable == 'Off'), fill = 'light blue') +
      geom_text(aes(x = 7, y = 0.15, label = "test")) +
      theme(plot.margin = unit(c(1,7,1,1), "lines")) +
      scale_y_continuous(limits = c(0.1, 0.2),
                         expand = c(0, 0),
                         oob = scales::oob_squish) +
      scale_x_continuous(limits = c(-5, 5), 
                         oob = scales::oob_keep) +
      coord_cartesian(clip = "off")
    

    reprex package (v0.3.0) 于 2020 年 12 月 25 日创建

    【讨论】:

    • 谢谢。有什么方法可以在 y 轴范围内移除受约束的水平线?
    猜你喜欢
    • 2014-03-03
    • 2011-05-31
    • 1970-01-01
    • 2013-12-22
    • 2011-03-20
    • 2020-10-08
    • 2018-08-07
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多