在 R 中着色直方图

Coloring Histograms in R

我正在尝试绘制以下数据:

library(ggplot2)

my_data <- data.frame( a = abs(rnorm(1000,17,10)),
b = a)

my_data$col = as.factor(ifelse(my_data$a > 17, "red", "blue"))

ggplot(my_data, aes(x=a)) + 
  geom_histogram(binwidth=1)

但由于某种原因,当我尝试添加颜色时,出现以下错误:

ggplot(my_data, aes(x=a)) + 
  geom_histogram(binwidth=1, color = my_data$col)

Error: Aesthetics must be either length 1 or the same as the data (59): colour

谁能告诉我如何解决这个错误?

谢谢

您可以将 cutscale_fill_manual 一起使用。

library(ggplot2)

my_data <- data.frame(a = abs(rnorm(1000,17,10)))
my_data$col = cut(my_data$a, c(-Inf, 17, Inf))

ggplot(my_data, aes(x=a, fill = col)) + 
  geom_histogram(binwidth=1) + 
  scale_fill_manual(breaks = levels(my_data$col), values = c('blue', 'red'))