编辑:按照建议进行修改
我正在尝试根据这篇文章创建一个简单的连续事件频率图:ggplot序列模式
我想堆叠相同的图表,但是针对其他主题(不同的序列)
主题"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)
我得到的结果是:
![我的结果,不好](https://istack.dev59.com/yynKE.webp)
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),需要创建数据框。正如您所看到的,每个主题的事件总数不一定相等。
![expected](https://istack.dev59.com/8x4kI.webp)