使用ggpattern和ggnewscale库,将geom_tile转化为geom_raster。
首先,安装ggpattern和ggnewscale库。然后使用新的ggpattern::geom_raster_pattern函数替换原来的ggplot2::geom_tile函数。代码示例如下:
library(ggplot2)
library(ggpattern)
library(ggnewscale)
创建数据
df <- data.frame(
x = rep(1:10, 10),
y = rep(1:10, each = 10),
z = rnorm(100)
)
使用ggplot2和ggpattern创建带有图案颜色填充的热力图
ggplot(df, aes(x, y, fill = z)) +
替换geom_tile为geom_raster_pattern,同时使用ggnewscale来切换scale_fill为图案填充
geom_raster_pattern(aes(pattern = z)) +
scale_fill_pattern() +
设置图例和标签
labs(title = "Heatmap with pattern fill",
x = "X",
y = "Y",
fill = "Z") +
theme_void()