我有一個資料集,其中包含一個隨時間變化的二進制變數(0 vs 1)。我想跨時間繪制 1 的出現。我們的想法是查看 1 在哪個時期出現得更頻繁。這是一個示例資料集:
set.seed(123)
dd <- data.frame(id = c(rep(1,100), rep(2,80), rep(3,90)),
time = c(seq(from=1,to=100), seq(from=1,to=80), seq(from=1,to=90)),
outcome = c(sample(c(0, 1), 100, replace = TRUE),
sample(c(0, 1), 80, replace = TRUE),
sample(c(0, 1), 90, replace = TRUE)))
我在想也許像這樣的
我的熱圖將有我的time變數而不是Dayx 軸,并且熱標度將反映 1 的頻率。對于我的示例資料集,因為 1 最常出現在第二個時間段中,它將被突出顯示為最熱的地方陰謀。
uj5u.com熱心網友回復:
這樣的事情有用嗎?
dd %>% group_by(time) %>% summarise(n_outcome = sum(outcome)) %>%
ggplot(aes(x = time, y = n_outcome)) geom_line()

您顯然可以對其進行調整以使其更漂亮
uj5u.com熱心網友回復:
不確定我是否完全理解您在尋找什么。是這樣的嗎:
library(tidyverse)
dd %>%
group_by(time) %>%
summarise(outcome=sum(outcome)) %>%
ggplot(aes(x=time, fill=outcome)) geom_tile(aes(y=1))
scale_x_continuous(breaks = 1:7) scale_fill_viridis_c(option='plasma')

它確實根據需要將第二個周期突出顯示為最高頻率 1。如果您需要將其拆分為幾個月(根據您的示例影像),則使用facet_wrap()或facet_grid()與相關的月份變數一起使用。
編輯:
要獲得更像問題中示例的熱圖,您需要另一個維度。在下面的示例中,我已將您的時間維度拆分為 2 個維度:
dd <- dd %>%
mutate(
period1=as.integer(time / 10) * 10 ,
period2=time %% 10
)
dd %>%
group_by(period1, period2) %>%
summarise(outcome=sum(outcome)) %>%
ggplot(aes(x=period1, y=period2, fill=outcome)) geom_tile()
scale_fill_viridis_c(option='plasma')
scale_x_continuous(breaks=seq(0,100,10)) scale_y_continuous(breaks=0:10)
這給出了以下輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530258.html
