gpt4 book ai didi

r - 如何使用 stat_contour 完全填充轮廓

转载 作者:行者123 更新时间:2023-12-03 20:51:19 25 4
gpt4 key购买 nike

我正在寻找完全填充由 ggplot2 的 stat_contour 生成的轮廓的方法。目前的结果是这样的:

# Generate data
library(ggplot2)
library(reshape2) # for melt
volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")

v <- ggplot(volcano3d, aes(x, y, z = z))
v + stat_contour(geom="polygon", aes(fill=..level..))

enter image description here

可以通过如下手动修改代码来产生所需的结果。
v + stat_contour(geom="polygon", aes(fill=..level..)) +
theme(panel.grid=element_blank())+ # delete grid lines
scale_x_continuous(limits=c(min(volcano3d$x),max(volcano3d$x)), expand=c(0,0))+ # set x limits
scale_y_continuous(limits=c(min(volcano3d$y),max(volcano3d$y)), expand=c(0,0))+ # set y limits
theme(panel.background=element_rect(fill="#132B43")) # color background

enter image description here

我的问题:有没有办法在不手动指定颜色或使用 geom_tile() 的情况下完全填充绘图?

最佳答案

正如@tonytonov 所建议的那样 thread ,可以通过关闭多边形来删除透明区域。

# check x and y grid
minValue<-sapply(volcano3d,min)
maxValue<-sapply(volcano3d,max)
arbitaryValue=min(volcano3d$z-10)

test1<-data.frame(x=minValue[1]-1,y=minValue[2]:maxValue[2],z=arbitaryValue)
test2<-data.frame(x=minValue[1]:maxValue[1],y=minValue[2]-1,z=arbitaryValue)
test3<-data.frame(x=maxValue[1]+1,y=minValue[2]:maxValue[2],z=arbitaryValue)
test4<-data.frame(x=minValue[1]:maxValue[1],y=maxValue[2]+1,z=arbitaryValue)
test<-rbind(test1,test2,test3,test4)

vol<-rbind(volcano3d,test)

w <- ggplot(vol, aes(x, y, z = z))
w + stat_contour(geom="polygon", aes(fill=..level..)) # better

# Doesn't work when trying to get rid of unwanted space
w + stat_contour(geom="polygon", aes(fill=..level..))+
scale_x_continuous(limits=c(min(volcano3d$x),max(volcano3d$x)), expand=c(0,0))+ # set x limits
scale_y_continuous(limits=c(min(volcano3d$y),max(volcano3d$y)), expand=c(0,0)) # set y limits

# work here!
w + stat_contour(geom="polygon", aes(fill=..level..))+
coord_cartesian(xlim=c(min(volcano3d$x),max(volcano3d$x)),
ylim=c(min(volcano3d$y),max(volcano3d$y)))

enter image description here

这个调整仍然存在的问题是寻找除了反复试验之外的方法来确定 arbitaryValue .

[从这里编辑]

只是一个快速更新,以显示我如何确定 arbitaryValue无需猜测每个数据集。
BINS<-50
BINWIDTH<-(diff(range(volcano3d$z))/BINS) # reference from ggplot2 code
arbitaryValue=min(volcano3d$z)-BINWIDTH*1.5

这对于我现在正在处理的数据集似乎很有效。不确定是否适用于其他人。另外,请注意,我在此处设置 BINS 值这一事实要求我必须使用 bins=BINSstat_contour .

关于r - 如何使用 stat_contour 完全填充轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28469829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com