我想要一個使重疊非常清晰的情節。更具體地說,我想繪制給定個人作業的地方。由于個人可能同時在不同的作業場所作業,我將為每個作業場所繪制一個 geom_line。我的問題是:當有重疊時我如何說清楚?我嘗試在 geom_line() 中使用一些透明度,但我正在尋找使重疊突出的東西
您可以在下面看到 3 個個人和 2 個作業場所的簡單示例。個人 A 從作業場所 1 切換到作業場所 2,個人 B 做同樣的事情,但中間有一段時間失業,個人 C 在兩個地方作業的時間很短(這是我看到重疊的地方)。
# individual A
a_id <- c(rep('A',25))
a_period <- c(seq(1, 13), seq(13,24))
a_workplace <-c(rep(1,13), rep(2,12))
# individual B
b_id <- c(rep('B',19))
b_period <- c(seq(2,8), seq(13,24))
b_workplace <-c(rep(1,7), rep(2,12))
# individual C
c_id <- c(rep('C',9))
c_period <- c(seq(1,4), seq(2,6))
c_workplace <-c(rep(1,4), rep(2,5))
# final affiliation data
id <- c(a_id, b_id, c_id)
period <- c(a_period, b_period, c_period)
workplace <- c(a_workplace, b_workplace, c_workplace)
mydata <- data.frame(id, period, workplace)
# affiliation data by workplace
mydata_1 <- mydata %>%
filter(workplace==1) %>%
mutate(workplace=as.factor(workplace))
mydata_2 <- mydata %>%
filter(workplace==2) %>%
mutate(workplace=as.factor(workplace))
我嘗試了下面的方法,但仍然想讓重疊部分更清晰。也許是顏色組合的建議,使重疊更清晰?
ggplot(mydata_1, aes(period, id, group=id, col=workplace))
geom_line(alpha=0.4)
geom_line(data=mydata_2, alpha=0.4, aes(period, id, group=id, col=workplace))
labs(x="time", y=NULL, title="Work affiliation")
scale_x_continuous(breaks = seq(0,24, by=2))
scale_y_discrete(limits=rev)
scale_color_manual(values=c("dodgerblue","firebrick1"))
theme(legend.position = c(.7, .92), legend.direction = "horizontal",
legend.background = element_rect(linetype="solid", colour ="black"),
panel.background = element_rect(fill = "grey97"))
我也不明白為什么我在圖例中看不到正確的作業場所顏色。
uj5u.com熱心網友回復:
我想我會組合資料集,然后geom_line用position_dodge. 這可以簡化您的代碼、顯示重疊并正確顯示您的圖例。
all_data <- rbind(mydata_1, mydata_2)
ggplot(all_data, aes(x = id, y = period, color = workplace))
geom_line(position = position_dodge(width = 0.1), size = 2)
labs(y = "time", title = "Work affiliation")
scale_y_continuous(breaks = seq(0, 24, by = 2))
scale_x_discrete(limits = rev)
scale_color_manual(values = c("dodgerblue", "firebrick1"))
coord_flip()
theme(legend.position = c(.7, .92),
legend.direction = "horizontal",
legend.background = element_rect(linetype = "solid", colour = "black"),
panel.background = element_rect(fill = "grey97"))

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