2015-06-11 54 views
1

我刚刚接触R,并试图在RStudio中通过使用包含多个变量的1000个观察值的数据集在单个图中生成多个条形图。下面是该数据集的片段:在R中创建多个图依赖于两个不同的分类变量

Municipality Production Type 
Atima   690   Reverification 
Atima   120   Reverification 
Atima   220   Reverification 
Comayagua  153   Initial 
Comayagua  193   Initial 
Comayagua  138   Initial 
Comayagua  307   Reverification 
Copán   179   Initial 
Copán   100   Initial 
Copán   236   Reverification 
Copán   141   Reverification 
Danlí   56   Reverification 
... 

数据集的结构

Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 1543 obs. of 3 variables: 
$ Municipality : chr "Atima" "Atima" "Atima" "Comayagua" ... 
$ Production  : num 98 690 153 307 179 ... 
$ Type   : chr "Reverification" "Reverification" "Reverification" "Initial" ... 

我想拿出是显示一对杆(每市1对)一barplot,一显示一个市政府在“Initial”中的生产量以及另一个显示“重新验证”的数量的酒吧。

我已经尝试了各种命令,如barplot,条形图和ggplot,但迄今没有成功。

我应该将Type变量分成2,1每个类别吗?我也试图绘制它仅取决于式生产,并收到以下消息:7

感谢

barplot(table(dataset$Production[dataset$Type=="Initial"]), names.arg = Municipality) 
Error in barplot.default(dataset$Production[dataset$Type=="Initial"]), names.arg = 
Municipality, : incorrect number of names 

我在Rstudio版本0.99.441工作,在Windows提前寻求你的帮助。

回答

1

试试这个:

library(ggplot2) 
library(data.table) 
df_s <- 
    as.data.table(df)[ , .("Production_Sum" = sum(Production)), 
         by = .(Municipality, Type)] 

ggplot(df_s, aes(x = Municipality, y = Production_Sum, fill = Type)) + 
    geom_bar(stat = "identity", position = position_dodge()) 

enter image description here

我使用(你在你的OP指定)以下数据:

df <- read.table(header = TRUE, text = "Municipality Production Type 
Atima   690   Reverification 
Atima   120   Reverification 
Atima   220   Reverification 
Comayagua  153   Initial 
Comayagua  193   Initial 
Comayagua  138   Initial 
Comayagua  307   Reverification 
Copán   179   Initial 
Copán   100   Initial 
Copán   236   Reverification 
Copán   141   Reverification 
Danlí   56   Reverification 
") 
+0

grrgrrbla嗨,我得到这个错误信息: 错误:ggplot2不知道如何处理类函数的数据 我的错误是什么?谢谢你的帮助。 –

+0

你应该使用的data.frame应该命名为df,你可以在ggplot-function-call的开头输入它,以便使用'ggplot(data = df,.....)',所以不用df你的data.frame被调用,我猜你的名字不是df,但有些不同,我编辑了这个问题来包含我使用的数据 – grrgrrbla

+0

这需要更多的工作,重新整理和总结数据......我编辑了我的文章,请接受通过点击嘀嗒标记并点击向上箭头来获得答案,点击向上箭头 – grrgrrbla

相关问题