繁体   English   中英

填充R中的轮廓图部分

[英]Filling parts of a contour plot in R

我用以下代码在R中绘制了轮廓图:

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

这就是等高线图的样子。

我想通过对图的某些部分进行阴影/着色来说明累积概率,例如区域{x<0, y<0} (或任何其他自定义区域)中的所有内容。

这是我寻求实现的徒手画图。

有什么办法可以通过ggplotR中实现这一ggplot吗?

因此,您可以使用ggplot_build获得用于在图中绘制圆的坐标。 随后,您可以尝试将这些坐标与geom_polygon结合使用以对特定区域进行geom_polygon 我最好的尝试:

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)

结果图

如您所见,这并不完美,因为[x,0][0,y]坐标未包含在数据中,但这只是一个开始。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM