R语言Bike_share 数据集记录了 2011 年 1 月 1 日到 2012 年 12 月 31 日华盛顿地 区每天各小时共享单车的租赁情况。其中变量 workingday = 0 表示非工作 日,workingday = 1 表示工作日,casual 为临时用户租车量,registered 为注册用户租车量,count 为总租车量(casual+registered)。(注:题中提 及的租车量,未特别说明的,均使用 count 变量) (1) 读入 Bike_share.xlsx 文件,并命名为 bike_share。 (2) 将 hour 变量因子化,并绘制箱线图比较各小时的总租车量。 (3) 增加一列 season,season 将 month 分为 4 组:1-3 月为"spring", 4-6 月为"summer",7-9 月为"autumn",10-12 月为"winter",将其 保存为 bike_share2,然后统计各季节的平均租车量。 (4) 绘制柱状图查看各小时租车量中各季节的占比,设置 position 参数使 得各柱子长度均相等。 (5) 绘制柱状图统计各小时的平均租车量,将工作日和非工作日分面,分面 呈现为 2 行。 (6) 将 date 变量转换成标准日期格式,然后按日期加总租车量,并绘制出 各天租车量的曲线图。
时间: 2024-03-17 13:43:26 浏览: 53
(1) 读入 Bike_share.xlsx 文件,并命名为 bike_share。
```R
library(readxl)
bike_share <- read_excel("Bike_share.xlsx")
```
(2) 将 hour 变量因子化,并绘制箱线图比较各小时的总租车量。
```R
# 因子化 hour 变量
bike_share$hour <- factor(bike_share$hour)
# 绘制箱线图
boxplot(count ~ hour, data = bike_share, main = "Total rentals by hour", xlab = "Hour", ylab = "Total rentals", col = "lightblue")
```
(3) 增加一列 season,season 将 month 分为 4 组:1-3 月为"spring",4-6 月为"summer",7-9 月为"autumn",10-12 月为"winter",将其保存为 bike_share2,然后统计各季节的平均租车量。
```R
# 根据 month 变量创建 season 变量
bike_share$season[bike_share$month %in% c(1, 2, 3)] <- "spring"
bike_share$season[bike_share$month %in% c(4, 5, 6)] <- "summer"
bike_share$season[bike_share$month %in% c(7, 8, 9)] <- "autumn"
bike_share$season[bike_share$month %in% c(10, 11, 12)] <- "winter"
# 将结果保存为 bike_share2
bike_share2 <- bike_share
# 统计各季节的平均租车量
aggregate(count ~ season, data = bike_share2, mean)
```
(4) 绘制柱状图查看各小时租车量中各季节的占比,设置 position 参数使得各柱子长度均相等。
```R
library(ggplot2)
# 统计各小时租车量中各季节的总量
season_hour <- aggregate(count ~ season + hour, data = bike_share2, sum)
# 计算各小时租车量中各季节的占比
season_hour_pct <- ddply(season_hour, .(hour), transform, percent = count / sum(count))
# 绘制柱状图
ggplot(season_hour_pct, aes(x = hour, y = percent, fill = season)) +
geom_bar(position = "dodge", stat = "identity") +
scale_fill_manual(values = c("spring" = "green", "summer" = "yellow", "autumn" = "orange", "winter" = "blue")) +
labs(title = "Seasonal proportion of rentals by hour", x = "Hour", y = "Proportion", fill = "Season")
```
(5) 绘制柱状图统计各小时的平均租车量,将工作日和非工作日分面,分面呈现为 2 行。
```R
# 统计各小时的平均租车量
hour_mean <- aggregate(count ~ hour + workingday, data = bike_share, mean)
# 绘制柱状图
ggplot(hour_mean, aes(x = hour, y = count, fill = workingday)) +
geom_bar(position = "dodge", stat = "identity") +
labs(title = "Average rentals by hour and working day", x = "Hour", y = "Average rentals", fill = "Workingday") +
facet_wrap(~ workingday, nrow = 2)
```
(6) 将 date 变量转换成标准日期格式,然后按日期加总租车量,并绘制出各天租车量的曲线图。
```R
# 将 date 变量转换成标准日期格式
bike_share$date <- as.Date(bike_share$date, "%m/%d/%Y")
# 按日期加总租车量
daily_rentals <- aggregate(count ~ date, data = bike_share, sum)
# 绘制曲线图
ggplot(daily_rentals, aes(x = date, y = count)) +
geom_line(color = "blue") +
labs(title = "Total rentals by day", x = "Date", y = "Total rentals")
```
阅读全文