R version 3.1.1 (2014-07-10) Platform: i386-w64-mingw32/i386 (32-bit)
我正在使用ggplot2
. 目的是为数据组合堆叠和闪避的条形图。我的问题是包含一个图例,它包括两个图层或分别显示它们。
数据:
df <- structure(list(year = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
1L, 2L, 3L, 4L, 5L, 6L, 7L), .Label = c("2008", "2009", "2010",
"2011", "2012", "2013", "2014"), class = "factor"), product = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("a",
"b"), class = "factor"), total = c(1663L, 1344L, 1844L, 444L,
1336L, 897L, 655L, 3433L, 3244L, 2044L, 3344L, 1771L, 1410L,
726L), partial = c(1663L, 1344L, 1844L, 444L, 949L, 302L, 5L,
3433L, 3244L, 2044L, 3344L, 1476L, 1158L, 457L)), .Names = c("year",
"product", "total", "partial"), row.names = c(NA, -14L), class = "data.frame")
计划是绘制两个 geom_bar 图层以结合闪避和堆叠。第一层是总量,第二层是部分量。降低第一层的 alpha 值以查看两层之间的差异。到目前为止,它奏效了。
例子:
ggplot(df, aes(x = year))+
geom_bar(aes(y = total, fill = product), alpha= 0.3, stat = "identity", position = "dodge", width = 0.3)+
geom_bar(aes(y = partial, fill = product), alpha= 1, stat = "identity", position = "dodge", width = 0.3)
现在传说还不够。它显示第一层的颜色fill = product
并且对第一层的alpha值不敏感。
我的方法是使用scale_fill_manual
并手动添加具有新颜色的新标签,但没有奏效。
我的想法:
ggplot(df, aes(x = year))+
geom_bar(aes(y = total, fill = product), alpha= 0.3, stat = "identity", position = "dodge", width = 0.3)+
geom_bar(aes(y = partial, fill = product), alpha= 1, stat = "identity", position = "dodge", width = 0.3)+
scale_fill_manual(name = "",
values=c("red", "black","blue"),
labels=c("a","b","test"))
感谢您对我的问题的任何帮助!