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

时间:2019-03-13 22:31:48

标签: r ggplot2 geom-bar

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

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

enter image description here

我发现我可以使这些条重叠,然后分别更改每个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)

enter image description here

第二个选项是我想要的,但是我不再有图例来显示颜色代表什么。如何像第二个示例一样有效地创建图表,但如何维护图例?

1 个答案:

答案 0 :(得分:7)

在主width中指定aes(您可以使用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"))

enter image description here

相关问题