geom_bar() 使条形宽度不同并完全重叠

geom_bar() make bars different widths and completely overlap

我有一些数据可以捕捉多个时间段内两个不同群体的百分比。

df <- structure(list(period = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 
3L, 4L, 5L), .Label = c("FY18 Q4", "FY19 Q1", "FY19 Q2", "FY19 Q3", 
"FY19 Q4"), class = "factor"), key = c("You", "You", "You", "You", "You", 
"Me", "Me", "Me", "Me", "Me"), value = c(0.707036316472114, 
0.650424585523655, 0.629362214199759, 0.634016393442623, 0.66578947368421, 
0.509574110529601, 0.505703612591682, 0.493109917284898, 0.497505296695832, 
0.523938932489946)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

我想绘制此数据,以便一个周期的两个条形图彼此重叠,但条形图的宽度不同。我希望 "Me" 的栏为 width=0.5,"You" 的栏为 width=0.7。我还想包括一个说明每种颜色代表什么的图例。

如果我想并排绘制条形图,我可以使用 position="dodge",如下所示:

library(ggplot2)
library(dplyr)

ggplot(data=df, aes(x=period, y=value, fill=key)) +
  geom_bar(stat="identity", position="dodge")

我发现我可以让条形重叠,然后单独更改每个 geom_bar() 的宽度,如下所示:

ggplot(data=df %>% filter(key=="You"), aes(x=period, y=value, color=)) +
  geom_bar(stat="identity", fill="gray50", width=.7) +
  geom_bar(data=df %>% filter(key=="Me"), stat="identity", fill="darkblue", width=0.5)

第二个选项是我想要的,但我不再有图例来显示颜色代表什么。我怎样才能像第二个例子那样高效地创建图表,但又要保留图例?

在 main aes 中指定 width(您可以使用 ifelse 传递想要的值):

library(ggplot2)
ggplot(df, aes(period, value, fill = key, width = ifelse(key == "You", 0.7, 0.5))) +
    geom_bar(stat = "identity") +
    scale_fill_manual(values = c("darkblue", "gray50"))