R堆积条形图与汇总数据

Mar*_*o M 7 aggregate r ggplot2

我在创建带有汇总数据的堆积条形图时遇到了麻烦.当处理来自其他人的报告的聚合表时,我通常使用Excel,但我想开始在R中做我的所有图表,可能使用格子或ggplot.在Excel中,执行以下聚合数据的堆叠条形图需要几次单击(插入,列图表,堆积列),您将得到类似的结果.在此输入图像描述.

除了想在这张图表中RI也希望用ggplot的刻面,即把两个堆叠barcharts并排ggplot比较两个组(A和B).I've与其他图表发挥各地,这似乎是最好的选择.这是数据.Excel图表仅显示组A(数字是百分比).

D<-as.data.frame(structure(list(Group = c("A", "A", "A", "A", "A", 
"A", "B", "B", "B", "B", "B", "B"
), Education = c("NVQ Level 4 and above", "NVQ Level3", "NVQ Level 2", 
"Below NVQ Level 2", "Other qualification", "No qualification", 
"NVQ Level 4 and above", "NVQ Level3", "NVQ Level 2", "Below NVQ Level 2", 
"Other qualification", "No qualification"), Full.Time = c(47, 
27, 23, 17, 18, 9, 36, 26, 22, 22, 27, 12), PT.16.hours = c(20, 
24, 22, 18, 18, 12, 22, 21, 21, 22, 14, 10), PT.16.hours.1 = c(12, 
11, 10, 11, 13, 5, 24, 25, 25, 20, 16, 12)), .Names = c("Group", 
"Education", "Full.Time", "PT>16.hours", "PT<16.hours")))
Run Code Online (Sandbox Code Playgroud)

在进入分面以显示两组之间的差异之前,我实际上遇到了使用ggplot2创建单个堆叠条形图(如上图所示)的麻烦.我猜我不应该有3个变量(FullTime,PT,PT> 16小时),而是每个案例的单行,所以不要

A    NVQ Level 4 and above      47  20  12
A    NVQ Level3                 27  24  11
Run Code Online (Sandbox Code Playgroud)

我应该

Group          Education    Work     Percentage
A   NVQ Level 4 and above   Full Time   47
A   NVQ Level 4 and above   PT>16 hours 20
Run Code Online (Sandbox Code Playgroud)

如果这是让ggplot完成图表的唯一方法,那么如何使用几行代码从一种格式转换到另一种格式?我经常会发现这种类型的数据,因此最好有一个标准化的程序.我也玩过ggplot选项'identity',但没有取得多大成功.

任何帮助将非常感激.

谢谢

dar*_*zig 8

reshape 你的数据:

library(reshape2)
df <- melt(D)
Run Code Online (Sandbox Code Playgroud)

并简单地绘制它:)

ggplot(df, aes(x = factor(Education), y = value, fill = factor(variable))) +
geom_bar() + facet_grid(.~Group) +
ylab('') + xlab('') + opts(title = '') + scale_fill_discrete('') +
theme_bw() +
opts(axis.text.x=theme_text(angle = 45, hjust = 1, vjust = 1))
Run Code Online (Sandbox Code Playgroud)

第一行创建集美学,第二行添加bar图层,facet第三行我们从图中删除不需要的文本,第4行设置b&w主题,最后一行我们旋转x asis标签.

在此输入图像描述