簡體   English   中英

多層geom_bar圖的自定義圖例

[英]Custom legend for multi layer geom_bar plot

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

在此處輸入圖片說明

感謝您對我的問題的任何幫助!

嘗試對總數據和部分數據使用不同的填充值。

快速而骯臟的解決方案:

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM