使用ggplot2绘制来自多个数据帧的闪避条

时间:2014-05-15 12:13:54

标签: r ggplot2 geom-bar

我有三个数据框,我实际上不能rbindcbind。它们共享列'Pop.Name',其中存储了种群名称。人口名称在三个dfs中很常见。

我正在尝试使用ggplot2来计算(stat="bin")每个数据帧中每个群体的个案数量,并绘制它以便我为每个df和每个群体设置不同的条形图。基本上我想比较每个人口的计数数据,就像在单个df和我使用geom_bar(position="dodge")处理dfs一样。

要绘制一个我正在使用的df:

plt<- ggplot(df1, aes(x=Pop.Name)) + theme_bw() # plot by pop
plt<- plt + geom_bar()

如何将其他两个dfs添加到同一个图中?我确信这很简单,我错过了一些东西,但无法弄清楚是什么。我试过了:

plot1 <- ggplot(df1, aes(x=Pop.Name)) + 
    geom_bar() +
    geom_bar(data = df2)

还有很多其他人,但我要么每次弹出都会出错或只有一个酒吧。如果这是重复的话,我非常抱歉,但我认为不是。但是,我的问题与此非常相似:ggplot stacked bar plot from 2 separate data frames,但我不能rbindcbind数据框(至少不是直接向前的方式,而且每个都是巨大的)。< / p>

由于

一些玩具数据:

df1<-structure(list(Pop.Name = c(1, 2, 3, 4, 3, 2, 1, 2, 3, 4), Loc = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 3L), .Label = c("a", "c", "d" ), class = "factor"), BP = c(10, 10, 10, 10, 50, 21, 33, 8, 8, 8)), .Names = c("Pop.Name", "Loc", "BP"), row.names = c(NA, -10L), class = "data.frame")

df2<-structure(list(Pop.Name = c(3, 2, 3, 4, 3, 2, 1), A = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 3L), .Label = c("x", "y", "z" ), class = "factor"), C = c(11, 11, 11, 10, 50, 21, 3)), .Names = c("Pop.Name", "A", "C"), row.names = c(NA, -7L), class = "data.frame")

1 个答案:

答案 0 :(得分:0)

这是一个选项:

df.list <- list(a=df1, b=df2)
dat <- stack(lapply(df.list, `[[`, "Pop.Name"))
ggplot(dat, aes(x=values, fill=ind)) + geom_bar(position="dodge")

首先我们将数据框放在一个列表中,然后我们只用Pop.Name[[提取lapply列,最后我们stack将它们重新转换为数据框架仅包含源数据框标签和Pop.Name。这会产生:

enter image description here

请注意,Pop.Names 不能是因素,因此可以使用。数据:

df1 <- data.frame(Pop.Name=sample(letters, 50, rep=T), stringsAsFactors=F)
df2 <- data.frame(Pop.Name=sample(letters, 50, rep=T), stringsAsFactors=F)

编辑:没有注意到您发布的数据,但这与您的数据一致。