MWE:
library(metR)
heat_palette = c("darkred", "red", "yellow", "#00A600", "darkgreen")
heatmap_of_percentage <- function(percent) {
# display <- sprintf("%2f%%", {{percent}})
# ^^ If I uncomment this, I get a bug
c(
geom_raster(aes(fill = {{percent}})),
geom_contour(aes(z = {{percent}}), color = "black"),
geom_text_contour(aes(z = {{percent}}), color = "black", stroke = 0.2),
scale_fill_gradientn(limits = c(0, 100), colours = heat_palette)
)
}
df <- expand.grid(x = 1:100, y = 1:100)
df$Z <- df$x * df$y / 100
ggplot(df, aes(x = x, y = y)) +
heatmap_of_percentage(percent = Z)
产生
我想修改它,以便轮廓被标记为10%、30%等。我该如何做到这一点,仅修改
heatmap_of_percentage
(即不在调用代码中添加额外的列)?
您可以使用
after_stat()
来格式化与 level
的值相对应的标签,该值是由 geom_text_contour
在引擎盖下计算的:
library(metR)
library(ggplot2)
heat_palette <- c("darkred", "red", "yellow", "#00A600", "darkgreen")
heatmap_of_percentage <- function(percent) {
c(
geom_raster(aes(fill = {{ percent }})),
geom_contour(aes(z = {{ percent }}), color = "black"),
geom_text_contour(
aes(
z = {{ percent }},
label = after_stat(sprintf("%.0f%%", level))
),
color = "black", stroke = 0.2
),
scale_fill_gradientn(limits = c(0, 100), colours = heat_palette)
)
}
df <- expand.grid(x = 1:100, y = 1:100)
df$Z <- df$x * df$y / 100
ggplot(df, aes(x = x, y = y)) +
heatmap_of_percentage(percent = Z)