如何在 R 中的 ggplot 上绘制分类变量频率

How to plot categorical variable frequency on ggplot in R

我正在尝试绘制一个折线图,显示从 2019 年 1 月到 2020 年 10 月在英格兰每个地区犯下的不同类型犯罪的频率。

结构如下:请想象有 9 个不同的区域,显然,有足够的月份来涵盖上述时间段。

    structure(list(Month = c("2019-01", "2019-01", "2019-01", "2019-01", 
"2019-01", "2019-01", "2019-01", "2019-01", "2019-01", "2019-01"
), Region = c("South West", "South West", "South West", "South West", 
"South West", "South West", "South West", "South West", "South West", 
"South West"), Crime = c("Anti social behaviour and sex offences", 
"Criminal damage and arson", "Criminal damage and arson", "Theft and burglary", 
"Theft and burglary", "Anti social behaviour and sex offences", 
"Anti social behaviour and sex offences", "Anti social behaviour and sex offences", 
"Other crime", "Anti social behaviour and sex offences")), row.names = c(NA, 
-10L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x000002d9ecd91ef0>)

它应该看起来像这样:

我意识到我的数据框中没有数字,所以 ggplot 可能不知道如何绘制每个月发生的盗窃和盗窃事件的数量。

知道如何解决这个问题吗? 在此先感谢您提供的任何帮助!

P.s。由于我需要分析 9 个区域,我正在考虑为每个单独的区域创建一个图,除非有一种视觉上可接受的方式将所有区域绘制在同一张图中?

尝试以下操作:

  1. 计算每个Month中每个RegionCrime个数。
  2. 通过添加任意日期值创建日期列。这对于在 x 轴上显示标签很有用。
  3. 在 x 轴上绘制 Date,在 y 轴上绘制 count,显示每个 Crime.
  4. 的不同颜色线条
  5. 为每个 Region 创建分面。
library(dplyr)
library(ggplot2)

df %>%
  count(Region, Month, Crime, name = 'count') %>%
  mutate(Date = as.Date(paste0(Month, '-01'))) %>%
  ggplot() + aes(Date, count, col = Crime) + 
  geom_line() + 
  facet_wrap(~Region) + 
  scale_x_date(date_labels = '%b %Y')