2

X、Y 和 Z 数据集使用geom_tile. 我想在值小于或等于 2 的图块周围画一条等高线。为此,我使用了该stat_contour函数,但结果不如预期。我怎样才能得到预期的结果?(最后一张图片)

library(ggplot2)

X <- 1:3
Y <- seq(0,20,10)

df <- expand.grid(X = X, Y = Y)

df$Z <- c(5,4,9,2.1,1.5,1.2,6,7,1.9)  

ggplot(df, aes(X, Y)) +
  geom_tile(aes(fill = Z)) +
  scale_fill_distiller(palette = "RdYlGn") +
  stat_contour(aes(z = Z),
               breaks = 2,
               color = 1)

在此处输入图像描述

我想要类似的东西:

在此处输入图像描述

4

1 回答 1

2

您可以尝试使用仅包含 Z <= 2 的行的数据子集添加不同的图层。最后一层是为了使瓷砖块内没有黑线(我在 geom_tile 中可能有一个参数不知道这样做)。

layer <- df %>% filter(Z <= 2)

ggplot(df, aes(X, Y)) +
  geom_tile(aes(fill = Z)) +
  scale_fill_distiller(palette = "RdYlGn") +
geom_tile(data=layer, alpha = 0.0, color = "black", size = 1, linejoin = "round") +
  geom_tile(data=layer, alpha = 1, aes(fill = Z)) 

在此处输入图像描述

于 2021-09-30T14:23:03.033 回答