2

我有一些我想使用 ggplot2 可视化的聚合数据,我现在正在寻找一个智能快捷方式来绘制聚合数据?

我拥有的数据看起来像这样,(我目前只有这样的数据df2

df <- data.frame(cyl = mtcars[,2])
(df2 <- t(table(df$cyl)))
      4  6  8
[1,] 11  7 14

我有兴趣创建一个这样的情节,(见下文code用于创建这个情节)

汇总数据上的 geom_bar

require(ggplot2)
df <- data.frame(cyl = mtcars[,2])
df$cyl2  <- ifelse(df$cyl > 4, c('Treatment'), c('Control'))
# hline.data <- data.frame(cyl2 = c('Treatment', 'Control'), cyl = c(10, 2))

c <- ggplot(df, aes(factor(cyl)))
c + geom_bar(fill="white", colour="darkgreen", alpha=0.5) + facet_grid(. ~ cyl2, scales = "free", space = "free") + theme(axis.title.x  = element_blank(), axis.title.y  = element_blank(), axis.ticks.x = element_blank(), legend.position = "none") + scale_y_continuous(breaks=c(4, 6, 8), labels=c("Minimal","Mild", "Moderate")) + scale_x_discrete(breaks=c(6,8,4), labels=c("Treat 1", "Treat 2", "Control")) 

对于做到这一点的人来说,这是一个额外的问题。是否有可能breaks=scale_y_continuous两个方面有所不同?geom_hline或者在边距中添加和添加一些文本会是更好的策略吗?似乎添加边距非常棘手,我必须像这样或和这样覆盖剪辑?

4

1 回答 1

1

您基本上只需要将聚合数据放入数据框中,然后添加组标签:

df <- data.frame(cyl = mtcars[,2])
(df2 <- t(table(df$cyl)))
# Assume you know the group labels
df2 <- data.frame(val=df2[1, ], label=c("Control", "Treat1", "Treat2"))
df2$cyl2 <- c("Control", "Treatment", "Treatment")

ggplot(df2, aes(label, val)) +
geom_bar(fill="white", colour="darkgreen", alpha=0.5, stat="identity") +
  facet_grid(. ~ cyl2, scales = "free", space = "free") +
  theme(axis.title.x  = element_blank(), axis.title.y  = element_blank(),
        axis.ticks.x = element_blank(), legend.position = "none") +
  scale_y_continuous(breaks=c(4, 6, 8), labels=c("Minimal","Mild", "Moderate")) +
  scale_x_discrete(breaks=c(6,8,4), labels=c("Treat 1", "Treat 2", "Control"))
于 2013-01-30T05:24:52.980 回答