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"))
感谢您对我的问题提供任何帮助!
答案 0 :(得分:0)
尝试对总数据和部分数据使用不同的填充值。
快速而肮脏的解决方案:
ggplot(df, aes(x = year))+
geom_bar(aes(y = total, fill = factor(as.numeric(product))), alpha= 0.3, stat = "identity", position = "dodge", width = 0.3) +
geom_bar(aes(y = partial, fill = factor(as.numeric(product) * 3)), alpha= 1, stat = "identity", position = "dodge", width = 0.3) +
scale_fill_manual(name = "", values=c("red", "black","blue", "green"), labels=c("A","B","Partial A", "Partial B"))
经过测试
R x64 3.2.2