【问题标题】:ggplot histogram colour by group not workingggplot直方图颜色按组不起作用
【发布时间】:2021-06-24 15:50:41
【问题描述】:

好的,我有这样的 df

a <- c(1,2,2,3)
b <- c(4,5,6,7)
ab <- data.frame(a, b)
ab 

我用 ggplot 绘制了一个简单的直方图,并尝试按 x 变量着色。

ggplot(ab, aes(x=a, fill=a)) +geom_histogram()

输出图不着色。我显然在某处犯了一个小错误。

【问题讨论】:

  • 在您的直方图中,应该只有一种颜色!不应该吗?
  • 试试ggplot(ab, aes(x=a, fill=as.factor(a))) +geom_histogram()

标签: r ggplot2 histogram


【解决方案1】:

另一种方式,a 需要考虑

    library(ggplot2)
    a <- c(1,2,2,3)
    b <- c(4,5,6,7)
    ab <- data.frame(a, b)
    ab 
    
    ggplot(ab, aes(x=a, fill=as.factor(a))) +
  geom_histogram()

【讨论】:

    【解决方案2】:

    我认为它可能更适用于条形几何。要使填充起作用,您可以将a 更改为一个因子。

    a <- c(1,2,2,3)
    b <- c(4,5,6,7)
    ab <- data.frame(a, b)
    ab 
    
    ggplot(ab, aes(x=a, 
                   fill=as.factor(a))) +
      geom_bar()
    

    【讨论】:

      猜你喜欢
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2021-08-28
      • 1970-01-01
      • 2021-08-04
      • 2016-06-14
      • 1970-01-01
      相关资源
      最近更新 更多