Different Legends for two geom_bar with different

2019-06-06 15:18发布

this one boggles my mind for quite a while ...

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

The first legend should have the title "border" (filled by border from df.1) and the second should have the title "product" (filled by product from df.2). Both data.frames have the column=category in common.

Can you shed some light?

Here is the 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)

标签: r ggplot2
1条回答
Evening l夕情丶
2楼-- · 2019-06-06 15:20

One aesthetic -> one legend is sort of a fundamental design principle in ggplot. You can (sort of) get around it, but it's difficult. One thing to try, that doesn't look too bad, is this:

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

查看更多
登录 后发表回答