代码之家  ›  专栏  ›  技术社区  ›  Bogaso

创建具有下限和上限的条形图

  •  2
  • Bogaso  · 技术社区  · 7 月前

    假设我有下面的情节

    library(ggplot2)
    library(zoo)
    dat = rbind(data.frame('Quarter' = as.yearqtr(as.Date(c('2000-01-01', '2002-01-01', '2004-01-01', '2006-01-01'))), 'Val' = c(10,20,30,40), 'Val_Lower' = c(10,20,30,40) - 5, 'Val_Upper' = c(10,20,30,40)+5, type = rep('A', 4)), 
                data.frame('Quarter' = as.yearqtr(as.Date(c('2000-01-01', '2002-01-01', '2004-01-01', '2006-01-01'))), 'Val' = c(10,20,30,40)-5, 'Val_Lower' = c(10,20,30,40)-5 - 5, 'Val_Upper' = c(10,20,30,40)+5-5, type = rep('B', 4)))
    
    ggplot(dat, aes(x = Quarter, y = Val)) +
      geom_point(aes(color = type)) +
      geom_ribbon(aes(fill = type, ymin = Val_Lower, ymax = Val_Upper), alpha = .3)
    

    然而,我希望为每个数据分别设置垂直条,而不是为下限和上限设置连续的带状线 type ,大致如下

    enter image description here

    有什么方法可以实现这种情节吗?

    1 回复  |  直到 7 月前
        1
  •  1
  •   M--    7 月前

    我们可以用 geom_linerange :

    ggplot(dat, aes(x = Quarter, y = Val, color = type)) +
      geom_linerange(aes(ymin = Val_Lower, ymax = Val_Upper), 
                     alpha = .3, linewidth = 15) +
      geom_point()
    

    创建于2024年12月23日 reprex v2.0.2