Different legends for two geom_bar with different data.frames

this one has been taking my mind for quite some time ...

I want to show two different legends for two different geometries (geom_bar) with different data frames.

The first legend should have the heading “border” (filled with the border from df.1), and the second should have the heading “product” (filled with the product from df.2). Both data.frames files have a common category column =.

Can you shed some light?

Here is an example

#library(ggplot2)

df.1 <- data.frame(category=c("A","A","A","B","B","B"),
border=c("I","II","III","I","II","III"),
value=c(1,2,1,2,1,2)
)

df.2 <- data.frame(category=c("A","A","A","B","B","B"),
product=c("P1","P2","P3","P1","P2","P3"),
value=c(1,2,3,3,1,2)
)

ggplot()+
geom_bar(aes(x=category, y=value, fill=border), data=df.1, width=.3)+
geom_bar(aes(x=category, y=value, fill=product), data=df.2, position="dodge", width=.25)
+1
source share
1 answer

One aesthetics → one legend - a kind of fundamental design principle in ggplot. You can (sort of) get around it, but it's hard. It's one thing to try, it doesn't look so bad:

ggplot()+
    geom_bar(aes(x=category, y=value, fill=border), data=df.1, width=.3)+
    geom_bar(aes(x=category, y=value, colour=product), data=df.2, position="dodge", width=.25,alpha = 0.5)

enter image description here

+4

All Articles