ggplot2 - 与堆叠和闪避的条形图 [英] ggplot2 - bar plot with both stack and dodge

查看:230
本文介绍了ggplot2 - 与堆叠和闪避的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用 ggplot2 创建一个barplot,我用一个变量堆叠,然后用另一个变量进行堆栈。



<下面是一个示例数据集:

pre $ data $ frame
year = rep(c(
treatment = rep(c(Impact,Control)),
type = rep(c(Phylum1,Phylum2), ),each = 2),
total = sample(1:100,8))

我想创建一个barplot,其中<​​code> x = treatment , y = total ,堆栈变量为 type ,闪避变量为 year

  ggplot(df,aes(y = total,x = treatment,fill =类型))+ geom_bar(position =dodge,stat =identity)

ggplot(df,aes(y = total,x = treatment,fill = year))+ geom_bar(position = dodge,stat =identity)

但不是两个!感谢任何能够提供建议的人。

解决方案

以下是使用faceting代替躲避的另一种方法:

  ggplot(df,aes(x = year,y = total,fill = type))+ 
geom_bar(position =stack,stat =identity)+
facet_wrap(〜处理)



随着泰勒建议的变化:




I am trying to create a barplot using ggplot2 where I am stacking by one variable and dodging by another.

Here is an example data set:

df=data.frame(
  year=rep(c("2010","2011"),each=4),
  treatment=rep(c("Impact","Control")),
  type=rep(c("Phylum1","Phylum2"),each=2),
  total=sample(1:100,8))

I would like to create a barplot where x=treatment, y=total, the stacked variable is type and the dodged variable is year. Of course I can do one or the other:

ggplot(df,aes(y=total,x=treatment,fill=type))+geom_bar(position="dodge",stat="identity")

ggplot(df,aes(y=total,x=treatment,fill=year))+geom_bar(position="dodge",stat="identity")

But not both! Thanks to anyone who can provide advice.

解决方案

Here's an alternative take using faceting instead of dodging:

ggplot(df, aes(x = year, y = total, fill = type)) +
    geom_bar(position = "stack", stat = "identity") +
    facet_wrap( ~ treatment)

With Tyler's suggested change:

这篇关于ggplot2 - 与堆叠和闪避的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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