【问题标题】:Custom legend for multi layer geom_bar plot多层 geom_bar 图的自定义图例
【发布时间】:2015-05-10 22:50:39
【问题描述】:

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

感谢您对我的问题的任何帮助!

【问题讨论】:

  • 您好,没有人可以帮忙吗?

标签: r plot ggplot2 legend geom-bar


【解决方案1】:

尝试对全部和部分数据使用不同的填充值。

快速而肮脏的解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多