构建带分组和时间线的条形堆叠图

Build Bar Stacked chart with grouping and timeline

我有一个 table:

> DT
id      start        end place
1: id1 2014-01-01 2014-02-01 town1
2: id1 2014-02-01 2014-04-01 town2
3: id2 2014-01-01 2014-02-01 town2
4: id2 2014-03-01 2014-05-01 town4
5: id3 2014-01-01 2015-02-01 town3

我需要用 X=timelineY=id 绘制图表,每一行应显示为一系列条形(长度取决于开始和结束日期,颜色取决于位置)。

图表示例:(没有时间轴标签):

例如,我正在尝试

ggplot(DT,aes(start,id,colour=place))+geom_bar()

当然不行

stat_count() must not be used with a y aesthetic.

我需要在图表中包含结束日期。

原始数据:

id1;2014-01-01;2014-02-01;town1
id1;2014-02-01;2014-04-01;town2
id2;2014-01-01;2014-02-01;town2
id2;2014-03-01;2014-05-01;town4
id3;2014-01-01;2015-02-01;town3

要使其正常工作,只需稍微更改 geom_bar:

ggplot(DT,aes(start,id, fill=place))+geom_bar(stat="identity")

话虽如此,您可能需要考虑其他时间线。在 r-bloggers 上尝试 this 博客 post。

你是认真的

start <- c("2014-01-01","2014-02-01","2014-01-01","2014-01-01","2014-02-01")
end <-  c("2014-02-01","2014-04-01","2014-02-01","2014-05-01","2014-03-01")
id <- c("id1","id1","id2","id2","id3")
evnt <- c("town1","town2","town2","town4","town3")
df<-data.frame(start,end,id,evnt)
p <- ggplot(df, aes(xmin=as.Date(start),xmax=as.Date(end),
                    ymin=as.numeric(id)-0.5,ymax=as.numeric(id)+0.5,
                    fill=evnt))+geom_rect()
p <- p+ylim(levels(df$id))

p

你举的例子没有包含可重现形式的数据框。因此,您可能需要适应 (c.f.https://whosebug.com/help/mcve)