我正在使用 ggplot 來繪制南美洲平均溫度的偏差。
為了繪制此圖,我使用以下代碼:
ggplot(bias.df2)
geom_tile(aes(x=x, y=y, fill=pr), alpha=0.8)
scale_fill_viridis(na.value="white")
coord_equal()
theme(legend.position="bottom")
theme(legend.key.width=unit(2, "cm"))
scale_color_continuous(limits=c(-10,10),breaks=brkbias)
這會生成以下顏色條:
但我需要彩條看起來像這樣:
我嘗試修改顏色條的限制,但似乎沒有任何東西可以生成我需要的那種情節。非常感謝任何幫助解決這個問題。
編輯:我正在使用的資料可以在這個 csv檔案中找到。
uj5u.com熱心網友回復:
guide_colorsteps()
可以與breaks =
引數結合使用scale_fill_viridis_c()
以列印具有連續填充的離散顏色條。我們可以修改注釋中鏈接的代碼,將三角形添加到該指南中。由于您有一個水平條,因此它需要水平移動和指向三角形而不是垂直。
library(ggplot2)
library(gtable)
library(grid)
bias.df2 <- read.csv("~/Downloads/data.csv")
my_triangle_colorsteps <- function(...) {
guide <- guide_colorsteps(...)
class(guide) <- c("my_triangle_colorsteps", class(guide))
guide
}
guide_gengrob.my_triangle_colorsteps <- function(...) {
# First draw normal colorsteps
guide <- NextMethod()
# Extract bar / colours
is_bar <- grep("^bar$", guide$layout$name)
bar <- guide$grobs[[is_bar]]
extremes <- c(bar$gp$fill[1], bar$gp$fill[length(bar$gp$fill)])
# Extract size
width <- guide$widths[guide$layout$l[is_bar]]
height <- guide$heights[guide$layout$t[is_bar]]
short <- min(convertUnit(width, "cm", valueOnly = TRUE),
convertUnit(height, "cm", valueOnly = TRUE))
# Make space for triangles
guide <- gtable_add_cols(guide, unit(short, "cm"),
guide$layout$t[is_bar] - 1)
guide <- gtable_add_cols(guide, unit(short, "cm"),
guide$layout$t[is_bar])
left <- polygonGrob(
x = unit(c(0, 1, 1), "npc"),
y = unit(c(0.5, 1, 0), "npc"),
gp = gpar(fill = extremes[1], col = NA)
)
right <- polygonGrob(
x = unit(c(0, 1, 0), "npc"),
y = unit(c(0, 0.5, 1), "npc"),
gp = gpar(fill = extremes[2], col = NA)
)
# Add triangles to guide
guide <- gtable_add_grob(
guide, left,
t = guide$layout$t[is_bar],
l = guide$layout$l[is_bar] - 1
)
guide <- gtable_add_grob(
guide, right,
t = guide$layout$t[is_bar],
l = guide$layout$l[is_bar] 1
)
return(guide)
}
ggplot(bias.df2)
geom_tile(aes(x=x, y=y, fill=pr), alpha=0.8)
scale_fill_viridis_c(na.value="white", limits = c(-10, 10),
breaks = c(-10, -7, -4, -1, -.5, .5, 1, 4, 7, 10),
guide = my_triangle_colorsteps(show.limits = TRUE))
coord_equal()
theme(legend.position="bottom")
theme(legend.key.width=unit(2, "cm"))
由reprex 包于 2022-06-01 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/485237.html
下一篇:R中的熱圖具有圖例和意義