我有一些我希望使用ggplot2可视化的汇总数据,我现在正在寻找一个智能捷径来绘制汇总数据?
我的数据看起来像这样(我目前只有像df2
这样的数据)
df <- data.frame(cyl = mtcars[,2])
(df2 <- t(table(df$cyl)))
4 6 8
[1,] 11 7 14
我有兴趣创建这样的情节,(见下面用于创建此情节的code
)
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
并在边距中添加一些文字是一种更好的策略吗?似乎添加边距非常棘手,我必须覆盖限幅like this或this?
答案 0 :(得分: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"))