Col*_*nch 4 r scale contour ggplot2
我想手动调整两个等值线图的比例,使每个等值线图具有相同的比例,即使它们在 z 方向包含不同范围的值。
例如,假设我想绘制 z1 和 z2 的等值线图:
x = 1:15
y = 1:15
z1 = x %*% t(y)
z2 = 50+1.5*(x %*% t(y))
data <- data.frame(
x = as.vector(col(z1)),
y = as.vector(row(z1)),
z1 = as.vector(z1),
z2 = as.vector(z2)
)
ggplot(data, aes(x, y, z = z1)) +
geom_contour_filled(bins = 8)
ggplot(data, aes(x, y, z = z2)) +
geom_contour_filled(bins = 8)
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以手动调整每个图的比例,使每个图包含相同数量的级别(在本例中 bins = 8),两者的最小值相同(在本例中为 min(z1)),并且两者的 max 相同 (max(z2))?
人们可以手动定义所需断点的向量,然后将该向量传递给函数中的“breaks”选项geom_contour_filled()。
在下面的脚本中,在数据集的最大最小值和最大最大值之间找到 8 个中断间隔。
此外,还定义了 2 个函数来为图例创建调色板和标签名称。
#establish the min and max of scale
grandmin <- min(z1, z2)-1
grandmax <- max(z2, z2)
#define the number of breaks. In this case 8 +1
mybreaks <- seq(grandmin, ceiling(round(grandmax, 0)), length.out = 9)
#Function to return the dersired number of colors
mycolors<- function(x) {
colors<-colorRampPalette(c("darkblue", "yellow"))( 8 )
colors[1:x]
}
#Function to create labels for legend
breaklabel <- function(x){
labels<- paste0(mybreaks[1:8], "-", mybreaks[2:9])
labels[1:x]
}
ggplot(data, aes(x, y, z = z1)) +
geom_contour_filled(breaks= mybreaks, show.legend = TRUE) +
scale_fill_manual(palette=mycolors, values=breaklabel(8), name="Value", drop=FALSE) +
theme(legend.position = "right")
ggplot(data, aes(x, y, z = z2)) +
geom_contour_filled(breaks= mybreaks, show.legend = TRUE) +
scale_fill_manual(palette=mycolors, values=breaklabel(8), name="Value", drop=FALSE)
Run Code Online (Sandbox Code Playgroud)