【问题标题】:Error bars on stacked barchart, using either plotly or ggplotly堆积条形图上的误差线,使用 plotly 或 ggplotly
【发布时间】:2020-01-21 11:17:58
【问题描述】:

我需要将一个简单的 ggplot 转换为小部件,一个带有不确定性的堆叠条。

数据:

 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)

和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')

当我尝试时:ggplotly(p2) 只转换堆叠条,而不是错误条。有什么建议吗?

或者,我可以使用plot_ly 创建绘图,但无法添加错误栏:

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

这会为堆叠直方图的所有份额产生误差条,而我只需要在堆叠直方图顶部出现一个错误。

感谢任何帮助

【问题讨论】:

    标签: r ggplot2 plotly ggplotly


    【解决方案1】:

    您可以准备一个每组只有一个错误大小的 data.frame

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

    并将错误绘制为单独的跟踪

    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')
    

    【讨论】:

      猜你喜欢
      • 2015-09-01
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多