You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ggplot中使用geom_tile时如何添加环绕每个色块的网格线?

在ggplot中实现corrplot风格的网格线

要复刻corrplot里环绕色块的网格线,核心思路是先铺一层满尺寸的白色背景tile,再在上方叠放你已经写好的缩放彩色tile,这样色块之间的白色间隙就会模拟出网格线的效果。

修改后的完整代码如下:

#create data
set.seed(100)
m <- matrix(runif(25, -1, 1), ncol = 5)
rownames(m) <- colnames(m) <- LETTERS[1:5]
m[lower.tri(m)] = t(m)[lower.tri(m)]
diag(m) <- 0

col1 <- colorRampPalette(RColorBrewer::brewer.pal(10,"BrBG"))

# Convert the correlation matrix to a data frame
df <- reshape2::melt(m)
df$abs <- abs(df$value)
df$Var1 <- factor(df$Var1, levels = colnames(m))

# Create a custom tile size function
tile_size <- function(x) {
  min_size <- 0.5
  max_size <- 1
  return((x - min(df$abs)) / (max(df$abs) - min(df$abs)) * (max_size - min_size) + min_size)
}

ggplot(df, aes(x = Var1, y = Var2)) +
  # 第一层:满尺寸白色tile,作为网格背景(可选加黑色边框更贴近corrplot)
  geom_tile(width = 1, height = 1, fill = "white", color = "black") +
  # 第二层:缩放后的彩色tile
  geom_tile(aes(fill = value, width = tile_size(abs), height = tile_size(abs))) +
  scale_x_discrete(position = "top") +
  scale_y_discrete(limits = rev(levels(df$Var1))) +
  scale_fill_gradientn(
    colors = col1(100),
    limits = c(-1,1)) +
theme_bw() +
theme(aspect.ratio = 1,
      panel.grid = element_blank()) # 关闭默认网格避免重叠

关键说明:

  • 第一层白色tile用width=1, height=1铺满整个绘图区域,加上color="black"可以还原corrplot的黑色细边框效果;
  • 关闭ggplot默认的panel.grid,避免和手动制作的网格线重叠;
  • 彩色tile叠放在白色tile上方,通过尺寸缩放留出的白色间隙,就是我们需要的网格线。

内容的提问来源于stack exchange,提问作者Electrino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:32:12