2

The clip function helps to set a clipping region in base graphics. For example, if I simulated a few observations in 2-d, I can plot only the observations in 4th quadrant in the following way:

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))

Created on 2019-07-04 by the reprex package (v0.3.0)

How can I do the same in ggplot2? I can of course filter the observations first, but I'm looking for a direct alternative.

yarnabrina
  • 1,561
  • 1
  • 10
  • 30
  • It seems to me that it will be quite useful in shading parts of the graph conditionally. I'm aware of [this post](https://stackoverflow.com/a/18009173/11117265), but for some situation, it may not be applicable. – yarnabrina Jul 04 '19 at 16:05
  • not sure there is a dedicated solution. You could use multiple `geom_rect()` on top of the points (`geom_rect(aes(xmin = -1, xmax = 0, ymin = -1, ymax = 1), fill = "grey90")` and so on...), but this can quickly become very very messy... filtering the data might be the best approach. – i94pxoe Jul 05 '19 at 08:25

1 Answers1

2

There is the filter solution, which you mentioned

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))

Does coord_cartesian provide a useful approach?

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) 

Alternatively, plot all the points in a colour that is the same as the background then overplot the points you need

  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
Tony Ladson
  • 3,539
  • 1
  • 23
  • 30
  • Thanks for answering. You missed a `+` after `geom_point` in the filtering solution. And, for the `coord_cartesian` approach, it just shows the 4th quadrant. Unless you can show me a way to show all the 4 quadrants, it's not useful for me. – yarnabrina Jul 05 '19 at 03:37
  • @yarnabrina, I've added another possible approach and fixed the missing `+` – Tony Ladson Jul 07 '19 at 22:04