efz
efz

Reputation: 435

Error bars on stacked barchart, using either plotly or ggplotly

I need to convert into widget a simple ggplot, a stacked bar with uncertainty.

The data:

 world.tot <- data.frame('country'='world', 'GHG'=c('CH4', 'CO2','N2O'), 
                         'emi'=c(6e+6, 3e+6, 1+6),
                         'unc.min'=8561406, 'unc.max'=14027350)

and the ggplot:

p2 <- ggplot(world.tot) +
        geom_bar(aes(x=country,y=emi,fill=GHG), stat='identity', position='stack' ) +
        geom_errorbar(aes(x=country, ymin=unc.min, ymax=unc.max), width=0.2) +
        theme(axis.title. x=element_blank(), axis.title. y=element_blank()) +
        theme(legend.position='none')

When I try: ggplotly(p2) only the stacked bars are converted, not the error bar. Any advice?

Alternatively, I could use plot_ly to create the plot, but cannot manage to add the error bar:

plot_ly(world.tot, x=~country. y=~emi, color=~GHG,type=bar,
        error_y=~list(array(c(unc.min, unc.max))) %>% 
  layout(barmode='stack')

This produces error bars to all shares of the stacked histogram, while I need only one error at the top of the stacked histogram.

Any help is appreciated

Upvotes: 1

Views: 348

Answers (1)

dww
dww

Reputation: 31452

You can prepare a data.frame that has only one error size per group

library(dplyr)
world.err <- world.tot %>%
  group_by(country) %>%
  summarise(emi = sum(emi), unc.min = 8561406, unc.max = 14027350)

And plot the errors as a separate trace

plot_ly(world.tot) %>%
  add_bars(x = ~country, y = ~emi, color = ~GHG, type='bar') %>%
  add_trace(x = ~country, y = ~emi, data = world.err,
              showlegend = F, mode='none', type='scatter',
              error_y = ~list(array = c(unc.min, unc.max), color = '#000000')) %>% 
  layout(barmode='stack')

enter image description here

Upvotes: 1

Related Questions