【问题标题】:Coloring Histograms in RR中的着色直方图
【发布时间】:2021-11-28 20:39:07
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: r ggplot2 data-visualization


    【解决方案1】:

    您可以将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'))
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多