如何使用此数据集在 R 中创建随时间变化的散点图

问题描述 投票:0回答:1

当我尝试以这种方式创建散点图时,它显示为一条平坦的线。这是我的数据的标题: see here

> 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))
r scatter-plot
1个回答
0
投票

您分配

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()
© www.soinside.com 2019 - 2024. All rights reserved.