在 R,ggplot2 中,如何将stat_density2d
几何对象中使用的网格更改为受三角形区域的约束?
我正在绘制不是标准 ggplot2 类型的三元图,轮廓溢出到轴上。实际三元图的代码很长,但本质上,我需要将轮廓限制为等边三角形。
这是重现该问题的示例代码:
library(ggplot2)
triangle <- data.frame(x=c(0,.5,1),y=c(0,1,0))
dummy <- data.frame(x=c(0.25,0.50,0.75),y=c(0.25,0.75,0.25))
p <- ggplot() + geom_polygon(data=triangle,aes(x,y),fill="transparent",color="black",size=1)
p <- p + geom_point(data=dummy,aes(x,y))
p <- p + stat_density2d(data=dummy,aes(x,y)) + theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.border = element_blank(), axis.ticks = element_blank(),
axis.text.x = element_blank(), axis.text.y = element_blank(),
axis.title.x = element_blank(), axis.title.y = element_blank())
p
我相信这是由于网格与绘图区域的原始笛卡尔坐标边界相关联,为了演示,请考虑以下代码:
library(ggplot2)
triangle <- data.frame(x=c(0,.5,1),y=c(0,1,0))
dummy <- data.frame(x=c(0.25,0.50,0.75),y=c(0.25,0.75,0.25))
p <- ggplot() + geom_polygon(data=triangle,aes(x,y),fill="transparent",color="black",size=1)
p <- p + geom_point(data=dummy,aes(x,y))
p <- p + stat_density2d(data=dummy,aes(x,y),geom='tile',contour=F,fill="transparent",color="magenta") + theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.border = element_blank(), axis.ticks = element_blank(),
axis.text.x = element_blank(), axis.text.y = element_blank(),
axis.title.x = element_blank(), axis.title.y = element_blank())
p
产生以下内容:
那么如何将网格更改为受三角形约束。而不是原始的笛卡尔绘图界限?