ZsideZ
ZsideZ

Reputation: 139

How to add zero count labels for unused factors?

I would like to create bargraph of the factor variable with count number on y axis. Also I would like to add count labels to the bars for all factors, including missing ones.

For example, code below generate the graph I need, but z factor has no label(it should be 0), so I would like to add it. ggplot2 version 2.2.1.9000

df <- data.frame(x = factor(c("x", "x", "x"), levels = c("x","z")))
ggplot(df, aes(x)) + stat_count() + 
  geom_text(stat = "count" ,aes(label = ..count..),vjust = -1)  + 
  scale_x_discrete(drop = FALSE)

Is it possible to do this without data transformations?

Upvotes: 0

Views: 549

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78822

Note:

library(ggplot2)

df <- data.frame(x = factor(c("x", "x", "x"), levels = c("x","z")))

ggplot(df, aes(x)) +
  stat_count() +
  scale_x_discrete(drop = FALSE) -> gg

This "computes" the plot:

gb <- ggplot_build(gg)

And, here's all that's available after the stat_count() calculation:

gb$data[[1]]
##   y count prop x PANEL group ymin ymax xmin xmax colour   fill size linetype alpha
## 1 3     3    1 1     1     1    0    3 0.55 1.45     NA grey35  0.5        1    NA

You don't have that data available (excerpt from stat_count()):

compute_group = function(self, data, scales, width = NULL) {
  x <- data$x
  weight <- data$weight %||% rep(1, length(x))
  width <- width %||% (resolution(x) * 0.9)

  count <- as.numeric(tapply(weight, x, sum, na.rm = TRUE))
  count[is.na(count)] <- 0

  data.frame(
    count = count,
    prop = count / sum(abs(count)),
    x = sort(unique(x)),
    width = width
  )
}

Either write a new stat_ or just do the computation outside of the plotting.

Upvotes: 3

Related Questions