I am trying to plot the following data:
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)
But for some reason, when I try to add colors, I get the following error:
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
Can someone please show me how to fix this error?
Thanks
CodePudding user response:
You may use cut
with scale_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'))