[英]Barplot in R/ggplot with multiple factors
I have a table which I would like to make into a plot using ggplot2 and I've been unsuccessful so far. 我有一张桌子,我想用ggplot2制作一个情节,到目前为止我还没有成功。 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 has 3 locations.Each location has 2 types of samples T1 or T2. Loc有3个位置。每个位置有2种类型的样本T1或T2。 They start in 2009 as A and over time some becomes B. So, by 2011, there are lots of B.
他们从2009年开始作为A,随着时间的推移,有些人成为B.因此,到2011年,有很多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. 我不太确定如何从三个因素中得到计数。
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.
facet是位置,我只为Loc1制作了条形图。
Try multi-level facets: 尝试多层次的方面:
df2 <- melt(df1, id.vars=c("Loc", "Type"))
ggplot(data=df2, aes(x=value, fill=Type)) +
geom_bar() + facet_wrap(~ Loc + variable, nrow=1)
Or alternatively, facet_grid
, which I think looks better but doesn't quite match your sketch: 或者,我认为
facet_grid
看起来更好但与你的草图不太匹配:
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)
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. 有一个包
ggextra
做了这样的东西,但它似乎不适用于最新的R版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.