2

I have made a contour plot in R with the following code:

library(mvtnorm)
# Define the parameters for the multivariate normal distribution
mu = c(0,0)
sigma = matrix(c(1,0.2,0.2,3),nrow = 2)

# Make a grid in the x-y plane centered in mu, +/- 3 standard deviations
xygrid = expand.grid(x = seq(from = mu[1]-3*sigma[1,1], to = mu[1]+3*sigma[1,1], length.out = 100),
                     y = seq(from = mu[2]-3*sigma[2,2], to = mu[2]+3*sigma[2,2], length.out = 100))

# Use the mvtnorm library to calculate the multivariate normal density for each point in the grid
distribution = as.matrix(dmvnorm(x = xygrid, mean = mu, sigma = sigma))

# Plot contours
df = as.data.frame(cbind(xygrid, distribution))
myPlot = ggplot() + geom_contour(data = df,geom="polygon",aes( x = x, y = y, z = distribution))
myPlot

This is what the contour plots look like.

I want to illustrate cumulative probability by shading/colouring certain parts of the plot, for instance everything in the region {x<0, y<0} (or any other self defined region).

Here is a free hand drawing of what I seek to achieve.

Is there any way of achieving this in R with ggplot?

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
andypatrol
  • 21
  • 1
  • There are similiar questions. Maybe they will help you: [similar question 1](https://stackoverflow.com/questions/9968975/make-the-background-of-a-graph-different-colours-in-different-regions) and [similar question 2](https://stackoverflow.com/questions/9178024/ggplot2-shade-area-between-two-vertical-lines) – luke Nov 20 '18 at 11:19

1 Answers1

0

So you are able to get the coordinates used to draw the circles in the plot using ggplot_build. Subsequently you could try to use these coordinates in combination with geom_polygon to shade a particular region. My best try:

library(dplyr)

data <- ggplot_build(myPlot)$data[[1]] 

xCoor <- 0
yCoor <- 0

df <- data %>% filter(group == '-1-001', x <= xCoor, y <= yCoor) %>% select(x,y)

# Insert the [0,0] coordinate in the right place
index <- which.max(abs(diff(rank(df$y))))
df <- rbind( df[1:index,], data.frame(x=xCoor, y=yCoor), df[(index+1):nrow(df),] )

myPlot + geom_polygon(data = df, aes(x=x, y=y), fill = 'red', alpha = 0.5)

Resulting plot

As you can see it's not perfect because the [x,0] and [0,y] coordinates are not included in the data, but it's a start.

Ravi
  • 81
  • 5