我有一些数据可以捕获多个时间段内两个不同组的百分比。
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)
第二个选项是我想要的,但我不再有一个图例来显示颜色代表什么。如何有效地创建第二个示例的图表,但保留图例?