已编辑:遵循建议
我试图根据这篇文章创建一个简单的连续事件频率图:ggplot sequence patterns
我想堆积相同的情节但是对于其他主题(不同的序列)
主题"aa", "bb", "cc"
示例数据集如下:
subject <- c("aa","aa","aa","aa","aa","aa","aa", "bb","bb","bb","bb","bb","bb","bb","cc","cc","cc","cc","cc","cc","cc")
event <- c("P","C","D","C","P","E","D","C","P","E","D","P","C","E","P","E","D","P","C","x","x")
freq <- c(3,2,1,4,2,1,0,3,4,1,3,3,1,2,1,3,2,1,4,0,0))
dfx <- data.frame(subject, event, freq)
我得到的结果是:
使用此代码,基于原始帖子:
library(ggplot2)
dfx$type <- factor(dfx$type)
dfx$ymin <- c(0,1,2)
dfx$ymax <- c(1,2,3)
dfx$xmax <- cumsum(dfx$count)
dfx$xmin <- c(0, head(dfx$xmax, n=-1))
plot_x <- ggplot(dfx,
aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,fill=type)) +geom_rect(colour="grey40", size=0.5)
png("plot_x.png", height=200, width=800)
print(plot_x)
dev.off()
我用我想要绘制的内容创建了这个图像。 (在excel手工制作)。在这种情况下,我们有3个主题,4个事件(C,P,D,E)+1虚拟事件(X),这是创建数据帧所必需的。如您所见,每个主题的事件总数不一定相等。
答案 0 :(得分:2)
尝试使用facet_grid
或facet_wrap
library(ggplot2)
p1 <-
ggplot(dfx, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = event))+
theme_bw() +
geom_rect(colour = "black", size = 0.5) +
facet_grid(subject ~ .) +
theme(axis.ticks.y=element_blank(), axis.text.y=element_blank())
p1
DATA:
dfx <- data.frame(
subject = c("aa","aa","aa","aa","aa","aa","aa", "bb","bb","bb","bb","bb","bb","bb","cc","cc","cc","cc","cc","cc","cc"),
event = c("P","C","D","C","P","E","D","C","P","E","D","P","C","E","P","E","D","P","C","x","x"),
freq = c(3,2,1,4,2,1,0,3,4,1,3,3,1,2,1,3,2,1,4,0,0),
ymin = 0,
ymax = 1)
TEMP <- tapply(dfx$freq,dfx$subject,cumsum)
dfx$xmax <- unlist(TEMP)
dfx$xmin <- c(0, head(TEMP$aa, -1), 0, head(TEMP$bb, -1), 0, head(TEMP$cc, -1))