Coloured tail with geom_histogram without a step

Viewed 161

There is a distribution and I like to colour the long tail from a specific value up to the end. When I use geom_histogram and aes(fill) with a 0-1-varibale I get a step.

Any Ideas how to prevent this?

Example:

set.seed(2713)
df <- data.frame(var_a = rnorm(n = 1000, mean = 10, sd = 2))
df2 <- data.frame(x = 12, y = 13)

ggplot() +
  geom_histogram(data = df, aes(var_a, fill = var_a > 12)) +
  geom_point(data = df2, aes(x = x, y = y), shape = 1, size = 15)

Histogram with coloured tail and step

1 Answers

You can apply the same logic after the statistic part of the layer has binned the data with after_stat().

library(ggplot2)

set.seed(2713)
df <- data.frame(var_a = rnorm(n = 1000, mean = 10, sd = 2))
df2 <- data.frame(x = 12, y = 13)

ggplot() +
  geom_histogram(data = df, 
                 aes(var_a, fill = after_stat(x > 12)))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2021-06-09 by the reprex package (v1.0.0)

Related