ggplot时间序列间隔堆叠的条形图

时间:2020-10-19 05:50:15

标签: r ggplot2

我有一个庞大的数据文件,我将其按人细分为多个日段,然后绘制当天发生的事件以及这些事件的持续时间(A,B或C)

数据的结构如下:t_z是行之间的间隔,period是事件变量,此示例适用于一天中的一个人(实际数据是xdays xpersons)

intervals <- c(0,5.1166667,6.2166667,3.5166667,0.06666667,3.0666667,6.3,
               2.3833333,0.06666667,4.7,18.666667,17.383333,21.533333,
               0.1,0.08333333,0.85)
period <- c("C",    "B",    "A",    "B",    "C",    "B",    "C",    "B",
            "C",    "B",    "C",    "B",    "C",    "B",    "C",    "B")
i <- as.data.frame(intervals)
p <- as.data.frame(period)
d <- cbind(i,p)

获取条形图很容易,但是它每天都会将所有“期间”堆积成块:

d$id<-1
e <- ggplot(d,aes(id))
e + geom_bar(aes(fill=period))

简单的聚合堆积时间条数据: Simple aggregated stacked bar of time data

但是,我希望每个“时期”都可以用其大小单独表示:

期间为离散堆积块示例: Periods as discrete stacked blocks example

感谢YBS,但是您的方法很接近,但是期间的大小并不正确吗?第一个C = 5与第一个A = 5的大小不同吗?

intervals <- c(5, 15, 5, 3,7,3,6, 2)
period <- c("C","B","A","B","C","B","C","B") 

d <- data.frame(intervals,period)
colors=c("red","blue","green")
dc <- data.frame(period=unique(d$period),colors)
d2 <- d %>% mutate(nid = paste0(d$period,'_',row_number()))
d3 <- left_join(d2,dc, by="period")
d3$id<-1

e <- ggplot(d3,aes(x=id, y=intervals)) +
  geom_col(aes(fill=nid)) 
e + scale_fill_manual(name='period', labels=d3$period, values=d3$colors )

Block sizes not in proportion to their interval values

1 个答案:

答案 0 :(得分:0)

诀窍是创建带有所有离散值的newid,然后通过scale_fill_manual返回到初始周期值。您可以使用coord_flip()使其水平,并根据需要更改图例位置。也许这是理想的输出。

intervals <- c(0, 5.1166667, 6.2166667, 3.5166667,0.6666667,3.0666667,6.3, 2.3833333)
               #,0.06666667 , 4.7,18.666667,17.383333,21.533333, 0.1,0.08333333,0.85)
period <- c("C",    "B",    "A",    "B",    "C",    "B",    "C",    "B") 
            # ,"C",    "B",    "C",    "B",    "C",    "B",    "C",    "B")

d <- data.frame(intervals,period)

colors=c("red", "blue","green")

dc <- data.frame(period=unique(d$period),colors)

d2 <- d %>% mutate(nid = paste0(d$period,'_',row_number()))

d3 <- left_join(d2,dc, by="period")

d3$id<-1

e <- ggplot(d3,aes(x=id, y=intervals)) +
       geom_col(aes(fill=nid)) 
e + scale_fill_manual(name='period', labels=d3$period, values=d3$colors )

output