简体   繁体   English

将等高线图限制为不同图的凸包

[英]Restrict contour plot to convex hull of a different plot

I have a contour plot in R. I would like to only show the region of this plot that lies inside the convex hull of a set of data-points from a different plot. 我在R中有一个等高线图。我想只显示该图的区域位于一组数据点的凸包内,来自不同的图。 All the region outside of this area should be blank (white). 该区域外的所有区域应为空白(白色)。

A reproducible example: 一个可重复的例子:

Here's the plot that produces the convex hull: 这是产生凸包的图:

ExampleValues <- matrix(sample(1:30), ncol = 2)
plot(ExampleValues)
hpts <- chull(ExampleValues)
hpts <- c(hpts, hpts[1])
lines(ExampleValues[hpts, ])

在此输入图像描述

Here's a different plot showing some contours (here using the package ' plotly '): 这是一个不同的图表,显示了一些轮廓(这里使用' plotly '包):

ContourPlotData <- data.frame(X = sample(1:50), Y = sample(1:50), Z = sample(1:100))
plot_ly(x = ContourPlotData$X, y = ContourPlotData$Y, z = ContourPlotData$Z, type = "contour")

在此输入图像描述

Now, I want to show only the part of the contour plot that is within the values specified by the convex hull from the first plot, and set all of the rest of the contour plot to be white. 现在,我想仅显示轮廓图的一部分,该部分位于第一个图中凸包指定的值内,并将轮廓图的所有其余部分设置为白色。 I would be very grateful if anyone has any advice as to how to do this. 如果有人对如何做到这一点有任何建议,我将非常感激。

A possibile solution in based on shapes inside layout . 基于layout内部shapes可能解决方案。 See here for details. 详情请见此处
An SVG path for the convex hull and the plot area must be defined. 必须定义凸包和绘图区域的SVG path The sintax is defined here . sintax 在这里定义。

set.seed(1)
df1 <- matrix(sample(15:46), ncol = 2)
hpts <- chull(df1)
hpts <- c(hpts, hpts[1])
df2 <- volcano

####
# Build the SVG path used in 'shapes'
####
nc <- ncol(df2)
nr <- nrow(df2)

# Plot area
xbox <- c(1, 1, nc, nc, 1)-1
ybox <- c(1, nr, nr, 1, 1)-1

# Convex hull
xpoly <- c(df1[hpts, 1])
ypoly <- c(df1[hpts, 2])

# SVG path (see https://www.w3schools.com/graphics/svg_path.asp )
pathbox <- c(paste0(xbox,",",ybox))
pathbox <- paste0(c("M",rep("L",length(pathbox)-1)), pathbox)

pathpoly <- c(paste0(xpoly,",",ypoly))
pathpoly <- paste0(c("M",rep("L",length(pathpoly)-1)), pathpoly)

SVGpath <- paste(c(pathpoly, pathbox,"Z"),collapse=" ")

library(plotly)
plot_ly(z=~df2, type = "contour") %>%
layout(shapes = list(
       list(type='path', path=SVGpath, fillcolor="white")
))

在此输入图像描述

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

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