【问题标题】:What is ggplot2 equivalent of graphics::clip什么是ggplot2相当于graphics::clip
【发布时间】:2019-07-04 16:05:17
【问题描述】:

clip 函数有助于在基本图形中设置剪切区域。例如,如果我在 2-d 中模拟了一些观察值,我可以通过以下方式仅绘制第 4 象限中的观察值:

dataset <- data.frame(x = runif(n = 100, min = -1, max = 1),
                      y = runif(n = 100, min = -1, max = 1))

plot(x = dataset, type = "n")
abline(h = 0, v = 0)
usr <- par('usr')
clip(x1 = 0, x2 = 1, y1 = -1, y2 = 0) # limits are sufficient for this toy example
points(x = dataset, pch = "x")

do.call(clip, as.list(x = usr))

reprex package (v0.3.0) 于 2019 年 7 月 4 日创建

我怎样才能在ggplot2 中做同样的事情?我当然可以先过滤观察结果,但我正在寻找直接的替代方案。

【问题讨论】:

  • 在我看来,它在有条件地对图形的某些部分进行着色时非常有用。我知道this post,但在某些情况下,它可能不适用。
  • 不确定是否有专门的解决方案。您可以在点的顶部使用多个geom_rect()geom_rect(aes(xmin = -1, xmax = 0, ymin = -1, ymax = 1), fill = "grey90") 等等......),但这很快就会变得非常混乱......过滤数据可能是最好的方法。

标签: r ggplot2 clip


【解决方案1】:

有你提到的过滤器解决方案

dataset %>% 
  filter(x > 0 & x < 1 & y > -1 & y < 0) %>% 
  ggplot(aes(x,y)) +
  geom_point() +
  geom_hline(yintercept = 0) +
  geom_vline(xintercept = 0) +
  scale_x_continuous(limits = c(-1,1)) +
  scale_y_continuous(limits = c(-1,1))

coord_cartesian 是否提供有用的方法?

dataset %>% 
  ggplot(aes(x,y)) +
  geom_point() +
  geom_hline(yintercept = 0) +
  geom_vline(xintercept = 0) +
  coord_cartesian(xlim = c(0,1), ylim = c(-1,0), expand = FALSE) 

或者,以与背景相同的颜色绘制所有点,然后覆盖您需要的点

  dataset %>% 
    ggplot(aes(x,y)) +
    geom_point(colour = 'white') + # white points
    geom_point(data = subset(dataset, subset = x > 0 & y < 0), colour = 'black') +
    geom_hline(yintercept = 0) +
    geom_vline(xintercept = 0) +
    theme_classic() # white background

【讨论】:

  • 感谢您的回答。您在过滤解决方案中错过了geom_point 之后的+。而且,对于coord_cartesian 方法,它只显示第四象限。除非你能告诉我一种显示所有 4 个象限的方法,否则它对我没有用处。
  • @yarnabrina,我添加了另一种可能的方法并修复了丢失的+
猜你喜欢
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多