Barplot in R/ggplot with multiple factors

2020-05-19 11:27发布

问题:

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 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.

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.

回答1:

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:

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.



标签: r ggplot2