在 ggplot 中多个条形图中添加组信息。

3
假设我有以下使用 ggplot 生成的多个条形图:
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)] 

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Names=c("Food","Music","People")     
data=data.frame(cbind(freq),Names)   
data=data[,c(5,3,1,2,4)]             


data.m <- melt(data, id.vars='Names')


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

目前的图表已经很好了。但是我想在x轴上添加一些分组信息。比如说定义了两个组:Group1 : 食品和音乐Group2 : 人物。我正在尝试构建一个如下所示的ggplot图表:

enter image description here

我还想减少食品与音乐之间的间隔,并增加音乐与人物之间的间隔,以便演示食品与音乐形成一个组,人物另一个组。

是否有办法使用ggplot框架实现这一点?

1个回答

4

有几种选项可以将群组信息作为标注添加到您的图中。但在我看来,一个很好的起点和最简单的方法是使用分面:

使用一些虚假的示例数据:

library(ggplot2)

variable <- c("Very Bad","Bad","Good","Very Good")

data.m <- data.frame(
  Names = rep(c("Food","Music","People"), each = 4),
  value = 1:12,
  variable = factor(variable, levels = variable)
)
data.m$group <- ifelse(data.m$Names %in% c("Food", "Music"), "Group 1", "Group 2")

ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity") +
  facet_grid(.~group, space = "free", scales = "free_x", switch = "x") +
  theme(strip.placement = "outside",
        strip.background.x = element_rect(fill = NA),
        strip.text.x = element_text(color = "red"))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接