我想手动调整两个等高线图的比例,使每个等高线图具有相同的比例,即使它们在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)
有什么方法可以让我手动调整每个图的比例尺 让每个图都包含相同数量的水平(在这种情况下,bins = 8),最小值是相同的(在这种情况下,min(z1)),最大值是相同的(max(z2))?
可以手动定义一个所需的断点向量,然后将该向量传递到 "断点 "选项中。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)