ggplot2等价于graphics :: clip

时间:2019-07-04 16:05:17

标签: r ggplot2 clip

clip功能有助于在基本图形中设置剪切区域。例如,如果我在2维中模拟了一些观测值,则可以通过以下方式仅绘制第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-07-04创建

如何在ggplot2中做同样的事情?我当然可以先过滤观察值,但我正在寻找直接的替代方法。

1 个答案:

答案 0 :(得分: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
相关问题