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

固定时间序列条形图的宽度

  •  0
  • Bogaso  · 技术社区  · 5 月前

    我有以下 ggplot

    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(1,2,3,4), type = rep('A', 4)), 
                data.frame('Quarter' = as.yearqtr(as.Date(c('2000-01-01',  '2004-01-01' ))), 'Val' = c(10,11), type = rep('B',2)))
    
    ggplot(dat, aes(x = Quarter, y = Val)) +
      geom_bar(aes(fill = type), position = 'dodge', stat = 'identity', width = .5)
    

    正如你所看到的,尽管存在争论,但条的宽度是不同的 width = .5 。我有时间序列数据,所以不想将x轴更改为因子。

    在当前设置中,是否有任何方法可以固定条形图的宽度。

    1 回复  |  直到 5 月前
        1
  •  1
  •   Allan Cameron    5 月前

    geom_bar(stat = "identity") 已被取代 geom_col() 7年前,但这在这里是偶然的。无论哪种情况,当您使用 position = "dodge" ,设置 width 参数将固定的宽度 每个闪避组 在x轴上。如果在某些x轴位置只有一个条,则其宽度为0.5。如果你在一个位置有两个条形图,它们加起来都是0.5(即每个条形图都是0.25)。

    要更改此设置,您需要将位置指定为 position = position_dodge(preserve = "single")

    ggplot(dat, aes(x = Quarter, y = Val, fill = type)) +
      geom_col(width = 0.5, position = position_dodge(preserve = "single"))
    

    enter image description here