R/ggplot中的条形图具有多个因素 [英] Barplot in R/ggplot with multiple factors

查看:95
本文介绍了R/ggplot中的条形图具有多个因素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张要使用ggplot2绘制成图表的表格,到目前为止,我一直没有成功. 我准备了一个简化的表格,看起来像这样

I have a table which I would like to make into a plot using ggplot2 and I've been unsuccessful so far. I have prepared a simplified table that looks like this

df1<-data.frame(Loc=c(rep("L1",5),rep("L2",3),rep("L3",4)),
Type=c(rep("T1",3),rep("T2",2),"T1","T2","T2","T1","T1","T2","T2"),
       y2009=rep("A",12),y2010=c("A","B","A","A","A","A","B","B","A","A","B","B"),
       y2011=c("B","B","B","A","B",rep("B",4),"A","B","B"))
df1

Loc有3个位置,每个位置都有2种类型的样本T1或T2.它们从2009年开始为A,随着时间的流逝,有些变为B.因此,到2011年,将会有很多B.

Loc has 3 locations.Each location has 2 types of samples T1 or T2. They start in 2009 as A and over time some becomes B. So, by 2011, there are lots of B.

这是我到目前为止的数字

This is the figure I have so far

ggplot(df1,aes(x=Type)) + geom_bar()+facet_grid(~Loc)
ggplot(df1,aes(x=y2009,fill=Type)) + geom_bar(position="dodge")+facet_grid(~Loc)

我不太确定如何从三个因素中获得计数.

I am not quite sure how to get counts from three factors.

我想要一个类似下面的图,我用油漆大致画了一个图.构面是位置,我仅以Loc1为例制作了条形图.

I would like a figure similar to below which I roughly drafted in paint. The facets are locations and I have made the bars only for Loc1 as example.

推荐答案

尝试多层面:

df2 <- melt(df1, id.vars=c("Loc", "Type"))
ggplot(data=df2, aes(x=value, fill=Type)) + 
  geom_bar() + facet_wrap(~ Loc + variable, nrow=1)

或者是facet_grid,我认为它看起来更好,但与您的草图不太匹配:

Or alternatively, facet_grid, which I think looks better but doesn't quite match your sketch:

df2 <- melt(df1, id.vars=c("Loc", "Type"))
ggplot(data=df2, aes(x=value, fill=Type)) + 
  geom_bar() + facet_grid(Loc ~ variable)

最后,从本文中借用 ,您可以尝试更好地通过颜色区分位置(显然,配色方案可能需要做一些工作,但是您明白了):

Finally, borrowing from this post, you could try to better distinguish the locations by color (clearly color scheme could use some work, but you get the point):

df2 <- melt(df1, id.vars=c("Loc", "Type"))
ggplot(data=df2, aes(x=value, fill=Type)) + 
  geom_rect(aes(fill=Loc),xmin =-Inf,xmax=Inf,ymin=-Inf,ymax=Inf,alpha = 0.1) +
  geom_bar() +
  facet_wrap(~ Loc + variable, nrow=1)

如果您想为每个位置实际使用单独的面板,我认为您将不得不使用生成自己的网格视口和grob.有一个软件包ggextra做了这样的事情,但是它似乎不适用于最新的R版本.

If you want to actually have separate panels for each location, I think you'll have to use generate your own grid viewports and grobs. There was a package ggextra that did stuff like this, but it doesn't seem to be available for the most recent R versions.

这篇关于R/ggplot中的条形图具有多个因素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆