【问题标题】:ggplot histogram showing extra grey barggplot 直方图显示额外的灰色条
【发布时间】:2015-11-05 18:44:59
【问题描述】:

所以我试图让这个直方图通过变量compage 显示。我正在使用的代码是这样的:

hist.wrinko.age <- ggplot(ESSdata.oldage3, aes(wrinco2,fill=compage))
                        + theme(legend.position = "right")
                        + geom_bar(aes(y=..density..), binwidth=1, position="dodge")
                        + labs(x="WRINCO by age group", y = "Density")
                        + scale_x_continuous(breaks=seq(0, 10, 1)
                          )

它工作正常,但直方图如下所示:

图例基本上显示2个变量,但直方图显示3个。

我不知道第三条灰线是从哪里来的 - 我的代码有问题吗?

【问题讨论】:

  • 很难说没有看到任何数据。我尝试使用 diamonds: ggplot(subset(diamonds, color %in% c("D", "E")), aes(x = carat, fill=color)) 与您的其余绘图命令进行复制,但看起来还不错。你的数据是什么样的? dput(head(ESSdata.oldage3, 20)) 会很好。
  • 数据如下所示: structure(list(wrinco2 = c(4, 7, 6, 10, 9, 8, 4, 8, 10, 4), rspslvo2 = c(7, 7, 6, 5, 8, 10, 5, 10, 5, 7), svclvo2 = c(2, 2, 2, 2, 2, 2, NA, 2, 0, 2), agea = c(27, 33, 53, 40, 36, 77, 20, 51, 49, 86), compage = 结构(c(1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L), .Label = c(" 0", "1"), class= "因子")), .Names = c("wrinco2", "rspslvo2", "svclvo2", "agea", "compage"), row.names = c("1 ", "2", "3", "4", "5", "6", "7", "8", "9", "10"), class= "data.frame")
  • 当我在您共享的数据上运行您的代码时,我看不到灰条。你能分享重现问题的数据吗?
  • 我的数据大约有43000行,所以不能全部分享——但都和上面的结构一样..
  • compage 向量应该包含 1 或 0。我刚刚检查过,0 和 1 的总数不等于总行数。想知道那里是否有一些流氓值。如何检查该列中是否有任何不是 1 或 0 的值?

标签: r ggplot2 histogram


【解决方案1】:

当有要绘制的数据(x 和 y 值)时添加灰色条,但 fill 变量为 NA

从数据中省略 NA 的最简单方法是 na.omit 函数

ggplot(na.omit(ESSdata.oldage3), ...

【讨论】:

    猜你喜欢
    • 2012-06-08
    • 2019-02-08
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多