我試圖將散點圖上的時間和日期軸排序為紀元/時間段。例如,12pm-:7:59pm 和 9pm-11:59pm 之間的時間。我想為日期做類似的事情。
我對 R 相當陌生,所以我只是在尋找建議/被告知這是否可能,也許還有一些替代方案:)
到目前為止,這是我的代碼:
accident <- read.csv("accidents.csv",header = TRUE)
accident <- accident %>%
ggplot(data=accident)
geom_point(mapping=aes(x=Time, y=Date, alpha=0.5))

謝謝!
uj5u.com熱心網友回復:
歡迎來到 R!這是一組選項。
library(tidyverse)
library(lubridate)
一、模擬資料集
accident <-
rnorm(n = 1000, mean = 1500000000, sd = 1000000) %>%
tibble(date_time = .) %>%
mutate(date_time = as.POSIXct(date_time, origin = "1970-01-01")) %>%
separate(date_time, into = c("date", "time"), sep = " ", remove = F)
原劇情:
accident %>%
ggplot()
geom_point(aes(x=time, y=date), alpha=0.5)

步驟 1:將 x 軸折疊成較少數量的組
accidents_per_trihour <-
accident %>%
mutate(hour = floor_date(date_time, unit = "hour"),
hour = as.numeric(str_sub(hour, 12,13)),
tri_hour = cut(hour, c(0, 3, 6, 9, 12, 15, 18, 21, 24), include.lowest = T)) %>%
group_by(date, tri_hour) %>%
count()
然后按事故數量縮放點大小
accidents_per_trihour %>%
ggplot()
geom_point(aes(x=tri_hour, y=date, size = n), alpha=0.5)
labs(x = "\nTime (in three-hour groups)", y = "Day\n", size = "Accidents count")

仍然不是很好,因為 y 軸太寬了。所以:
第 2 步:將 y 軸折疊為較少數量的組
(對于您的資料,您可能需要將其分組為幾個月才能開始看起來合理)
accidents_per_trihour_per_week <-
accident %>%
mutate(hour = floor_date(date_time, unit = "hour"),
hour = as.numeric(str_sub(hour, 12,13)),
tri_hour = cut(hour, c(0, 3, 6, 9, 12, 15, 18, 21, 24), include.lowest = T)) %>%
mutate(week_start = floor_date(as.Date(date), unit = "weeks"),
week = format.Date(week_start, "%Y, week %W")) %>%
group_by(week, tri_hour) %>%
count()
現在應該更具可讀性我們也會改進主題,只是因為。
if (!require(ggthemr)) devtools::install_github('cttobin/ggthemr')
ggthemr::ggthemr("flat") ## helps with pretty theming
accidents_per_trihour_per_week %>%
ggplot()
geom_point(aes(x=tri_hour, y=week, size = n), alpha = 0.9)
labs(x = "\nTime (in three-hour groups)", y = "Week\n", size = "Accidents count")

也可以做一個平鋪圖
accidents_per_trihour_per_week %>%
ggplot()
geom_tile(aes(x = tri_hour, y = week, fill = n))
geom_label(aes(x = tri_hour, y = week, label = n), alpha = 0.4, size = 2.5, fontface = "bold")
labs(x = "\nTime (in three-hour groups)", y = "Week\n", fill = "Accidents count")

由reprex 包(v2.0.1)于 2021 年 11 月 24 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/365606.html
下一篇:將文本標記與單詞串列匹配
