r - ggplot2 相当于graphics::clip 是什么

标签 r ggplot2 clip

clip 函数有助于在基础图形中设置剪切区域。例如,如果我在二维中模拟一些观测值,我可以通过以下方式仅绘制第四象限中的观测值:

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 于 2019-07-04 创建(v0.3.0)

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

最佳答案

这是您提到的过滤解决方案

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

关于r - ggplot2 相当于graphics::clip 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56891449/

相关文章:

javascript - JavaScript 中的 style.clip 随时间变化

r - 对于不同的 Redis 服务器构建,doRedis 在 Windows 8 x64 中返回错误

r - R中同一时间序列图有多种颜色,可能吗?

r - 如何更改ggplot2中图例文本的大小?

r - R : fill underneath a geom_smooth line 中的 ggplot2

performance - j2me : what is effect of 'g.clipRect()' on speed?

r - 提取字符和空格之间的元素

R:从函数内部在 globalenv() 中创建环境

r - 在 R 中绘制逻辑回归曲线

flutter - 如何使用 flutter 绘制自定义形状的小部件