gpt4 book ai didi

r - ggplot时间序列间隔堆积条

转载 作者:行者123 更新时间:2023-12-05 06:10:27 26 4
gpt4 key购买 nike

我有一个庞大的数据文件,我按人将其分解为一天中的 block ,然后绘制当天发生的事件和这些事件的持续时间(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)

获取条形图很容易,但它会按天将所有“周期”堆叠到 block 中:

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

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

但是,我希望每个“周期”都由其大小离散表示:

周期作为离散堆叠 block 示例: 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

最佳答案

诀窍是创建一个包含所有离散值的 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

关于r - ggplot时间序列间隔堆积条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64421797/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com