简体   繁体   中英

Custom legend for multi layer geom_bar plot

R version 3.1.1 (2014-07-10) Platform: i386-w64-mingw32/i386 (32-bit)

I am working on a barplot with ggplot2 . The aim is to have a combination of a stacked and dodged barplot for the data. My problem is to include a legend, which includes both layers or shows them separately.

Data:

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

The plan was, to plot two geom_bar layers to combine dodge and stacked. The first layer is the total amount, the second layer is the partial amount. The alpha value for the first layer is reduced to see the difference between the two layers. So far it worked.

Example:

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)

在此处输入图片说明

Now the legend is not sufficiant. It shows the colour of fill = product and is not sensitive to the alpha value of the first layer.

My approach was to use scale_fill_manual and manually add a new lable with a new colour, which did not worked.

My idea:

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

在此处输入图片说明

Thank you for any help on my problem!

Try to use different fill values for total and partial data.

Quick and dirty solution:

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

Tested on

R x64 3.2.2

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM