2017-09-21 76 views
0

我有一些数据,我已经尝试了一个filled.contour情节,这似乎很好。然而,传说很难控制,所以我想用ggplo2。但我不知道如何使用ggplot2来绘制filled.contour如何使用ggplot2绘制filled.contour图?

数据包含840行(代表日期)和12列(代表12个时间尺度)。下面是一个例子

set.seed(66) 
Mydata <- sample(x=(-3:3),size = 840*12,replace = T) 
Mydata <- matrix(data=Mydata,nrow=840,ncol=12) 
Dates <- seq(from=1948+1/24, to= 2018,by=1/12) 
data.breaks <- c(-3.5,-2.5,-1.5,0,1.5,2.5,3.5) 
filled.contour(Dates,seq(1:12),Mydata,col=cols(11),xlab="",ylab="time-scale",levels=data.breaks) 

enter image description here

我们可以看到,传说间隔是不是我想要的。我想在图例上显示-3.5,-2.5,-1.5,0,1.5,2.5,3.5,我相信用ggplot2这样做更容易。谢谢你的帮助。

回答

4

A ggplot2替代filled.contour的是stat_contour

library(ggplot2) 
library(reshape2) 
set.seed(66) 
Mydata <- sample(x=(-3:3),size = 840*12,replace = T) 
Mydata <- matrix(data=Mydata,nrow=840,ncol=12) 
Dates <- seq(from=1948+1/24, to= 2018,by=1/12) 
data.breaks <- c(-3.5,-2.5,-1.5,0,1.5,2.5,3.5) 
rownames(Mydata) <- Dates 

d <- melt(Mydata) 
colfunc = colorRampPalette(c("brown", "red", "yellow", "white")) 
ggplot(d, aes(Var1, Var2, z=value, fill = value)) + 
    stat_contour(geom="polygon", aes(fill=..level..)) + 
    scale_fill_gradientn(colours = colfunc(7), breaks=data.breaks, limits=c(-4,4), 
          values=scales::rescale(data.breaks))+ 
    theme_bw() + 
    scale_x_continuous(name="", breaks=seq(1950,2010,20), expand=c(0,0)) + 
    scale_y_continuous(name="time-scale", expand=c(0,0))+ 
    guides(fill = guide_colorbar(barwidth = 2, barheight = 15)) 

enter image description here

+0

非常感谢你的帮助。但我想知道如何获得我想要的传奇故事?谢谢。 –

+0

顺便说一句,'ggplot2'绘制的图与'filled.contour'绘制的图完全不同,你能解决这个问题吗?非常感谢。 –

+0

@YangYang什么意思是“完全不同”?我用'filled.contour'复制了它,但我发现只有很小的差异。请给我更多的细节。 –