具有不同data.frames的两个geom_bar的不同图例

时间:2012-12-27 23:47:25

标签: r ggplot2

这一次令人难以置信......

我想为具有不同data.frames的两个不同的geom(geom_bar)显示两个不同的图例。

第一个传奇应该有标题" border" (由df.1的边界填充),第二个应该有标题" product" (由df.2的产品填写)。两个data.frames都具有共同的column = category。

你能解决一些问题吗?

以下是示例

#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 个答案:

答案 0 :(得分:4)

一种美学 - &gt;一个传说在ggplot中是一种基本的设计原则。你可以(有点)绕过它,但这很困难。要尝试的一件事,看起来并不太糟糕,是:

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

相关问题