[英]Manually Set Scale of contour plot using geom_contour_filled
我想手動調整兩個等高線圖的比例,即使它們在 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)
有沒有辦法我可以手動調整每個 plot 的比例,使每個包含相同數量的級別(在本例中 bin = 8),兩者的最小值相同(在本例中 min(z1)),並且兩者的最大值相同(max(z2))?
可以手動定義所需斷點的向量,然后將向量傳遞給geom_contour_filled()
function 中的“breaks”選項。
在下面的腳本中,在數據集的最小值和最大值之間找到 8 個中斷間隔。
此外,還定義了 2 個函數來創建調色板和圖例的 label 名稱。
#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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.