将轮廓图限制为其他图的凸包

时间:2019-02-14 15:08:53

标签: r ggplot2 plotly r-plotly

我在R中有一个等高线图。我只想显示该图的区域,该区域位于不同图的一组数据点的凸包内。该区域之外的所有区域均应为空白(白色)。

可复制的示例:

以下是生成凸包的图:

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

enter image description here

这是另一幅显示一些轮廓的图(此处使用包“ 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")

enter image description here

现在,我只想显示轮廓图的一部分,该部分在第一个图的凸包指定的值之内,并将其余所有轮廓图设置为白色。如果有人对如何操作有任何建议,我将不胜感激。

1 个答案:

答案 0 :(得分:3)

基于shapes内部layout的可能解决方案。有关详细信息,请参见here
必须定义凸包和绘图区域的SVG path。语法定义为here

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

enter image description here