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

时间:2021-01-07 10:33:10

标签: r ggplot2 categorical-data

我试图绘制一个折线图,显示从 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>)

它应该看起来像这样:

enter image description here

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

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

附言因为我需要分析 9 个区域,所以我想为每个单独的区域创建一个图,除非有一种视觉上可接受的方式在同一图中绘制所有区域?

1 个答案:

答案 0 :(得分:1)

尝试以下操作:

  1. 为每个 Crime 中的每个 Region 计算 Month 的数量。
  2. 通过添加任意日期值来创建日期列。这对于在 x 轴上显示标签很有用。
  3. 在 x 轴上绘制 Date,在 y 轴上绘制 count,显示每个 Crime 的不同颜色线。
  4. 为每个 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')