ggplot中的分组条形图

时间:2013-08-10 03:50:03

标签: r ggplot2 bar-chart reshape reshape2

我有一个调查文件,其中的行是观察和列问题。

以下是一些fake data

People,Food,Music,People
P1,Very Bad,Bad,Good
P2,Good,Good,Very Bad
P3,Good,Bad,Good
P4,Good,Very Bad,Very Good
P5,Bad,Good,Very Good
P6,Bad,Good,Very Good

我的目标是用ggplot2创建这种情节。

  • 我绝对不关心颜色,设计等
  • 该图与假数据不对应

enter image description here

以下是我的假数据:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

但是,如果我选择Y作为计数,那么我面临一个关于选择X和组值的问题......我不知道如果不使用reshape2我是否能成功...我已经也厌倦了使用具有融化功能的重塑。但我不明白如何使用它......

1 个答案:

答案 0 :(得分:78)

首先,您需要获取每个类别的计数,即每个组(食物,音乐,人物)有多少坏和物品等。这将是这样做的:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

然后你需要从中创建一个数据框,融化并绘制它:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

这就是你要追求的吗?

enter image description here

为了澄清一点,在ggplot multiple grouping bar中你有一个如下所示的数据框:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

由于您在第4-9列中有数值,稍后将在y轴上绘制,因此可以使用reshape轻松转换并绘制。

对于我们当前的数据集,我们需要类似的内容,因此我们使用freq=table(col(raw), as.matrix(raw))来获取此内容:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

想象一下,您有Very.BadBadGood等等,而不是X1PCEX2PCEX3PCE。看到相似度?但我们首先需要创建这样的结构。因此freq=table(col(raw), as.matrix(raw))