当我尝试以这种方式创建散点图时,它显示为一条平坦的线。这是我的数据的标题:
> head(seattle_thefts)
# A tibble: 6 × 2
report_date_time offense
<dttm> <chr>
1 2020-02-04 13:54:37 Motor Vehicle Theft
2 2020-02-04 13:11:35 Motor Vehicle Theft
3 2020-02-04 09:46:13 Motor Vehicle Theft
4 2020-02-03 16:02:33 Motor Vehicle Theft
5 2020-02-03 15:49:24 Motor Vehicle Theft
6 2020-02-03 13:16:00 Motor Vehicle Theft
如何按月或年创建每次事件随时间变化的图?例如,散点图显示 2020 年 1 月、2020 年 2 月等发生的次数。
这只会创建一条扁平线:
ggplot(seattle_thefts, aes(x = report_date_time, y = offense)) +
geom_point()
我尝试将其更改为数值:
seattle_thefts$offense <- mutate(seattle_thefts, offense = 1)
seattle_thefts %>%
group_by(month = floor_date(report_date_time, 'month')) %>%
summarize(sum_of_thefts = sum(offense))
您分配
offense
与 mutate
的更改的方式看起来很奇怪,因为它会根据 tibble
的数据类型返回 data.frame
或 seattle_thefts
。完成“更改”后尝试查看seattle_thefts
。
我刚刚修改了你的做法
mutate()
seattle_thefts <- seattle_thefts %>% mutate( offense = 1)
seattle_thefts %>%
group_by(month = floor_date(report_date_time, 'month')) %>%
summarize(sum_of_thefts = sum(offense)) %>%
ggplot(aes(month,sum_of_thefts ))+
geom_point()
这是一个更短的替代方案,您不需要更改为数字,只需使用
n()
来计算每个分组的行数 month
seattle_thefts %>%
group_by(month = floor_date(report_date_time, 'month')) %>%
summarize(sum_of_thefts =n()) %>%
ggplot(aes(month,sum_of_thefts ))+
geom_point()