条形图:将一个堆叠条形图与一个躲避条形图结合起来

ott*_*eng 2 r ggplot2

我正在尝试重新创建以下报告第 4 页上的条形图:

在此输入图像描述

该人物有三个条形,前两个堆叠在一起,第三个则躲在旁边。我见过这个问题的迭代,但没有一个以这种精确的方式重新创建这个数字。

这是数据:

a <- rep(c('RHB', 'FERS', 'CSRS'), 3)
b <- c(rep('Assets', 3), rep('Amount Past Due', 3), 
       rep('Actuarial Liability', 3))
c <- c(45.0, 122.5, 152.3, 47.2, 3.4, 4.8, 114.4, 143.4, 181.3)

df <- data.frame(a,b,c)
names(df) <- c('Fund', 'Condition', 'Value')
Run Code Online (Sandbox Code Playgroud)

到目前为止我已经做到了:

p <- ggplot(subset_data, aes(fill=Condition, y=Value, x=Fund)) + 
  geom_bar(position="stack", stat="identity") + 
  coord_flip() 
Run Code Online (Sandbox Code Playgroud)

我并不偏爱,ggplot所以如果有另一个工具效果更好,我可以使用另一个包。

nni*_*loc 5

从 @aosmith 发布的链接中获取一些想法。

您可以调用geom_bar两次,一次使用AssetsAmounts Past Duestacked,再次使用 just Actuarial Liability

您可以使用width使条形变细,然后微移一组条形,以便两个geom_bar调用不会重叠。我选择调整宽度0.3并微移,0.3以便边缘对齐。如果你进一步推动,你会看到两个条之间有一个间隙。

编辑:添加更多格式和数字标签

library(tidyverse)
library(scales)

df_al  <- filter(df, Condition == 'Actuarial Liability')
df_xal <- filter(df, Condition != 'Actuarial Liability')

bar_width <- 0.3
hjust_lab <- 1.1
hjust_lab_small <- -0.2 # hjust for labels on small bars

ggplot() + 
  theme_classic() +
  geom_bar(data = df_al, 
           aes(fill=Condition, y=Value, x=Fund),
           position = position_nudge(x = -bar_width),
           width = bar_width,
           stat="identity") +
  geom_bar(data = df_xal, 
           aes(fill=Condition, y=Value, x=Fund),
           position="stack", 
           stat="identity",
           width = bar_width) +
  geom_text(data = df_al, 
            aes(label= dollar(Value, drop0trailing = TRUE), y=Value, x=Fund),
            position = position_nudge(x = -bar_width),
            hjust = hjust_lab) +
  geom_text(data = df_xal, 
            aes(label= dollar(Value, drop0trailing = TRUE), y=Value, x=Fund),
            position="stack",
            hjust = ifelse(df_xal$Value < 5, hjust_lab_small,  hjust_lab)) +
  scale_fill_manual(values = c('firebrick3', 'lightsalmon', 'dodgerblue')) +
  scale_y_continuous(breaks = seq(0,180, by = 20), labels = dollar) +
  coord_flip() +
  labs(x = NULL, y = NULL, fill = NULL) +
  theme(legend.position = "bottom")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述