【发布时间】:2014-12-19 16:37:55
【问题描述】:
我一直在学习 ggplot2,并希望将它用于我所有的 R 绘图。但是,我还没有找到一种方法来制作看起来类似于传统等高线图的等高线图,就像可以使用 lattice:filled.contour() 获得的一样。例如:
#define data
x<-seq(1,11,1)
y<-seq(1,11,1)
xyz.func<-function(x,y) {-10.4+6.53*x+6.53*y-0.167*x^2-0.167*y^2+0.0500*x*y}
#contour plot using lattice graphics and R Color Brewer
library(lattice) #for filled.contour()
library(RColorBrewer) #for brewer.pal()
z.lattice<-outer(x,y,xyz.func)
filled.contour(x,y,z.lattice,nlevels=6,col=brewer.pal(6,"YlOrRd"))
这给了我一个很好的等高线图。
现在,让我们在 ggplot2 中尝试同样的事情。根据我读过的所有内容(特别是Drawing labels on flat section of contour lines in ggplot2),我能想到的最好的是:
#contour plot using ggplot2
library(ggplot2)
library(reshape2) #for melt()
z.molten<-melt(z.lattice)
names(z.molten) <- c("x", "y", "z")
v<-ggplot(z.molten, aes(x,y,z=z))+
geom_tile(aes(fill=z))+
stat_contour(bins=6,aes(x,y,z=z), color="black", size=0.6)+
scale_fill_gradientn(colours=brewer.pal(6,"YlOrRd"))
v
这个图和fill.contour()有同样的基本思想,但是彩色的瓦片不太符合轮廓。
我也没有成功更改图块的大小。
关于如何使 ggplot2 的输出更接近 fill.contour() 的输出有什么建议吗?
【问题讨论】:
-
感谢 MrFlick 添加图表!
-
感谢@jlhoward 的建议。当我尝试将 geom=polygon 与 stat_contour() 一起使用时,我最终得到了多边形轮廓,但也许我使用不正确。例如,
ggplot(z.molten, aes(x,y,z=z))+stat_contour(geom="polygon",bins=6,aes(x,y,z=z))使轮廓为多边形。