我一直在学习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此图的基本思想与filled.contour()相同,但彩色瓦片与轮廓的一致性不是很好。

我也没有成功地改变瓷砖的大小。
关于如何使ggplot2的输出更接近filled.contour()的输出,有什么建议吗?
发布于 2014-12-20 01:56:38
你的问题的实质似乎是如何在ggplot中生成具有离散填充等高线的等高线图,而不是像使用传统的geom_tile(...)方法那样产生连续的等高线。这里有一种方法。
x<-seq(1,11,.03) # note finer grid
y<-seq(1,11,.03)
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}
gg <- expand.grid(x=x,y=y)
gg$z <- with(gg,xyz.func(x,y)) # need long format for ggplot
library(ggplot2)
library(RColorBrewer) #for brewer.pal()
brks <- cut(gg$z,breaks=seq(0,100,len=6))
brks <- gsub(","," - ",brks,fixed=TRUE)
gg$brks <- gsub("\\(|\\]","",brks) # reformat guide labels
ggplot(gg,aes(x,y)) +
geom_tile(aes(fill=brks))+
scale_fill_manual("Z",values=brewer.pal(6,"YlOrRd"))+
scale_x_continuous(expand=c(0,0))+
scale_y_continuous(expand=c(0,0))+
coord_fixed()

例如,scale_x_continuos(...)的使用只是为了消除ggplot在轴限制周围设置的额外空间;对于大多数事情来说都很好,但在等高线图中会分散注意力。使用coord_fixed(...)只是为了将宽高比设置为1:1。这些都是可选的。
https://stackoverflow.com/questions/27570221
复制相似问题