Reputation: 1
I'm plotting my data in a heatmap. Some of the data of the fill is positive and some is negative. I would like to plot a line over the heatmap that separates what is positive and what is negative.
I have looked up and tried using geom_contour, but couldn't figure out if there was an argument where to introduce the condition fill>0 or something like that. this is my current plot.
I would like a line that separates positive fron negative tiles like this
but keeping the color gradient of the oiginal, just plotting a line that separates both spaces.
Upvotes: 0
Views: 216
Reputation: 585
You can compute in a separate dataframe the threshold of y
above which the fill value is positive and add it to your plot with geom_step()
:
library(dplyr)
library(ggplot2)
df <- data.frame(x = rep(1:5, 5),
y = rep(1:5, each = 5),
z = -12:12)
ggplot(df, aes(x = x, y = y, fill = z)) +
geom_tile() + scale_fill_viridis_c() + theme_minimal()
df2 <- df %>%
filter(z >= 0) %>%
group_by(x) %>%
filter(y == min(y)) %>%
mutate(x = x - .5, y = y - .5) %>%
arrange(x)
df2 <- df2 %>% bind_rows(df2[nrow(df2), ] %>% mutate(x = x + 1))
df2
# A tibble: 6 x 3
# Groups: x [6]
x y z
<dbl> <dbl> <int>
1 0.5 3.5 3
2 1.5 3.5 4
3 2.5 2.5 0
4 3.5 2.5 1
5 4.5 2.5 2
6 5.5 2.5 2
ggplot() +
geom_tile(data = df, aes(x = x, y = y, fill = z)) +
geom_step(data = df2, aes(x = x, y = y), size = 2) +
scale_fill_viridis_c() + theme_minimal()
Upvotes: 0