Дифференцированная заливка цвета в geom_histogram () - PullRequest
0 голосов
/ 06 августа 2020

У меня есть следующий код для гистограммы с использованием ggplot2:

ggplot(data = x,
       aes(x = x)) +
  geom_histogram(fill = "navy",
                 alpha = 0.5) +
  theme_minimal() +
  geom_vline(xintercept = seq(30, 70, by = 10),
             linetype = "dashed")

, который отображает:

введите описание изображения здесь

Я хочу закрасить другим цветом полосы между интервалами, определяемыми вертикальными линиями. Например: полосы в интервале [30,40] должны быть желтыми, полосы в интервале (40,50] - оранжевыми и так далее ...

Кто-нибудь знает, как я могу достичь это?

Заранее спасибо.

1 Ответ

1 голос
/ 06 августа 2020

Давайте сначала попробуем вывести ваши данные, поскольку вы не указали это в своем вопросе:

library(ggplot2)

set.seed(69)

x <- data.frame(x = rnorm(5000, 50, 10))

ggplot(data = x,
       aes(x = x)) +
  geom_histogram(fill = "navy",
                 alpha = 0.5) +
  theme_minimal() +
  geom_vline(xintercept = seq(30, 70, by = 10),
             linetype = "dashed")

That's close enough for demonstration purposes.

It would be very difficult (though not impossible) to keep the plot the shape it is and color differently between the lines. It would also make little sense to have different colors within bins. However, it is fairly easy to do (and makes more sense) if you line up the bins with the vertical lines. Effectively we just manually bin and tabulate the data and plot it however we like:

df <- setNames(as.data.frame(table(1.25 + 2.5 * floor(x$x/2.5))), c("bin", "count"))

ggplot(df, aes(x = as.numeric(as.character(bin)), y = count, fill = bin)) +
  geom_col(width = 2.5) +
  theme_minimal() +
  geom_vline(xintercept = seq(30, 70, by = 10),
             linetype = "dashed") +
  scale_fill_manual(values = rep(c(rep("gray75", 3),
                               rep(c("yellow", "gold", "orange", "red"), each = 2),
                               rep("gray75", 4)), each = 2),
                    guide = guide_none()) + 
  labs(x = "x")

enter image description here

Created on 2020-08-06 by the пакет REPEX (v0.3.0)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...