Yan*_*ang 1 plot r legend ggplot2
我有一些数据,并且尝试了一个filled.contour看起来不错的情节。然而,图例很难控制,所以我正在考虑使用ggplo2。但我不知道如何绘制filled.contourusing ggplot2。
数据包含 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)
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,图例间隔不是我想要的。我想-3.5,-2.5,-1.5,0,1.5,2.5,3.5在图例上展示,我相信用 来做到这一点要容易得多ggplot2。谢谢你的帮助。
的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))
Run Code Online (Sandbox Code Playgroud)