Skip to content
Prev 277552 / 398506 Next

geom_bar with missing data in package ggplot

Hi:

Here's one way, but it puts the two countries side by side rather than
stacked (I'm not a big fan of stacked bar charts except in certain
contexts). The first version uses the original data, but one can see
immediately that there is no distinction between NA and 0:

ggplot(g, aes(x = Date, y = value, fill = var2)) +
    geom_bar(position = 'dodge', stat = 'identity') +
    facet_wrap(~ variable, nrow = 1) +
    scale_fill_manual('Country', breaks = levels(g$var2),
                                 values = c('red', 'blue')) +
    opts(legend.position = c(0.87, 0.88),
         legend.background = theme_rect(fill = 'white'))

To compensate, I copied the data to a new object g2 and imputed a
small negative value to replace the zero:

g2 <- g
g2$value[8] <- -0.01
ggplot(g2, aes(x = Date, y = value, fill = var2)) +
    geom_bar(position = 'dodge', stat = 'identity') +
    facet_wrap(~ variable, nrow = 1) +
    scale_fill_manual('Country', breaks = levels(g2$var2),
                                 values = c('red', 'blue')) +
    opts(legend.position = c(0.87, 0.88),
         legend.background = theme_rect(fill = 'white'))

An additional improvement could be made by keeping the original data
and adding some text that indicates where the NAs reside; to do this,
we need to offset the date a bit to decently locate the text:

ggplot(g, aes(x = Date, y = value, fill = var2)) +
    geom_bar(position = 'dodge', stat = 'identity') +
    facet_wrap(~ variable, nrow = 1) +
    scale_fill_manual('Country', breaks = levels(g$var2),
                                 values = c('red', 'blue')) +
    geom_text(aes(x = as.Date('2001-3-31'), y = 1, label = 'NA'),
               size = 6) +
    opts(legend.position = c(0.87, 0.88),
         legend.background = theme_rect(fill = 'white'))

HTH,
Dennis



On Wed, Nov 16, 2011 at 1:55 AM, Aidan Corcoran
<aidan.corcoran11 at gmail.com> wrote: