我有自行车数据,看起来像这样 - 数据框的尺寸很大.
> dim(All_2014)
[1] 994367 10
> head(All_2014)
X bikeid end.station.id start.station.id diff.time stoptime starttime
1 1 16379 285 356 338387 2014-01-02 15:22:28 2014-01-06 13:22:15
2 2 16379 361 146 47631 2014-01-09 22:45:34 2014-01-10 11:59:25
3 3 16379 268 327 5089 2014-01-10 12:35:22 2014-01-10 14:00:11
4 4 16379 398 324 715924 2014-01-22 14:34:55 2014-01-30 21:26:59
5 5 15611 536 445 716031 2014-01-02 15:30:44 2014-01-10 22:24:35
6 6 15611 348 433 68544 2014-01-12 14:03:01 2014-01-13 09:05:25
midtime Hour Day
1 2014-01-04 14:22:21 14 Saturday
2 2014-01-10 05:22:29 5 Friday
3 2014-01-10 13:17:46 13 Friday
4 2014-01-26 18:00:57 18 Sunday
5 2014-01-06 18:57:39 18 Monday
6 2014-01-12 23:34:13 23 Sunday
我的目标是使用ggplot2(或其他包装,如果它更适合)创建一个热图,看起来像这样,一周中的星期几在y轴上,小时在x轴上(小时没有在上午/下午,它可以保持24小时规模:
方框的填充是一个百分比,表示在给定的小时间隔内的骑行量/一周中当天的总骑行量.我已经设法使用这些数据,但想知道查找百分比的最简单方法,然后,如何使用它们创建热图.
使用dplyr进行计算,使用ggplot2进行计算:
library(dplyr)
library(ggplot2)
## First siimulate some data
rider_num <- 1:10000
days <- factor(c("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"),
levels = rev(c("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")),
ordered = TRUE)
day <- sample(days, 10000, TRUE,
c(0.3, 0.5, 0.8, 0.8, 0.6, 0.5, 0.2))
hour <- round(rbeta(10000, 1, 2, 6) * 23)
df <- data.frame(rider_num, hour, day)
## Use dplyr functions to summarize on days and hours to get the
## percentage of riders per hour each day:
df2 <- df %>%
group_by(day, hour) %>%
summarise(n=n()) %>%
mutate(percent_of_riders=n/sum(n)*100)
## Plot using ggplot and geom_tile, tweaking colours and theme elements
## to your liking:
ggplot(df2, aes(hour, day)) +
geom_tile(aes(fill = percent_of_riders), colour = "white") +
scale_fill_distiller(palette = "YlGnBu", direction = 1) +
scale_x_discrete(breaks = 0:23, labels = 0:23) +
theme_minimal() +
theme(legend.position = "bottom", legend.key.width = unit(2, "cm"),
panel.grid = element_blank()) +
coord_equal()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1374 次 |
| 最近记录: |