Reputation: 2279
An X, Y, and Z dataset was plotted using geom_tile
. I want to make a contour line around the tiles with values less than or equal to 2. For this, I used the stat_contour
function, but the result was not as expected. How can I get the expected result? (last image)
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)
I want something like:
Upvotes: 2
Views: 574
Reputation: 475
You could try adding a different layer with a subset of the data containing only the rows where Z <= 2. The last layer is so that there are no black lines within the block of tiles (there might be an argument in geom_tile that I am not aware of that does this).
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))
Upvotes: 2