【问题标题】:Dodged barplot with zero counts in ggplot2ggplot2中计数为零的闪避条形图
【发布时间】:2017-05-29 17:06:22
【问题描述】:

假设我们有以下玩具数据结构:

data <- structure(list(value = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L), class = structure(c(1L, 1L, 1L, 
2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("A", 
"B"), class = "factor")), .Names = c("value", "class"), class = "data.frame", row.names = c(NA, 
-16L))

在此数据中,一个分组的计数为零(即,B 类没有计数值为 3):

> library(dplyr)
> count(data, value, class)
Source: local data frame [5 x 3]
Groups: value [?]

  value  class     n
  <int> <fctr> <int>
1     1      A     3
2     1      B     3
3     2      A     4
4     2      B     2
5     3      A     4

下面的代码绘制了条形图(在 y 轴上具有相对频率),但我需要为零计数显示空白区域。相反,ggplot2 消除了计数为零的条形图。有什么建议如何包含零计数?

ggplot(data, aes(value, fill = class)) +
geom_bar(aes(y = ..count../sapply(fill, FUN=function(x) sum(count[fill == x]))), position="dodge")

这个问题与过去的类似问题(例如,Don't drop zero count)有关,但建议的解决方案在这里不起作用。

【问题讨论】:

  • 预先计算值不起作用?听起来是个挑战。 :)
  • 我正在寻找更程序化的解决方案。
  • 糟糕,忘记计算相对频率。查看我的(新)编辑。

标签: r ggplot2 bar-chart


【解决方案1】:

这样程序化够吗?我预先计算并绘制了所有内容...请注意,table“计数”为零的因子组合没有数据。

library(ggplot2)
xy <- table(data$class, data$value)
xy <- as.data.frame(xy)

xy$rel.freq <- xy$Freq / aggregate(Freq ~ Var1, FUN = sum, data = xy)$Freq

ggplot(xy, aes(x = Var2, y = rel.freq, fill = Var1)) +
  theme_bw() +
  scale_fill_brewer(palette = "Set1") +
  geom_bar(stat = "identity", position = "dodge")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多