在 R 中创建具有相对频率/来自 Table 对象的条形图

Create Bar Chart With Relative Frequency / From Table Object in R

我有一个关于英国事故的数据集。在其他变量中,它包含事故发生的月份和严重程度(范围从 1 到 3)。因此,你可以想象这样的数据集:

ID Month Accident_Severity
1 01 3
2 01 2
3 04 1
4 07 2

我想制作一个条形图,其中 x 轴为月份,y 轴为本月发生的给定严重程度 class 之外的事故的相对比例。这意味着每个月应该有三个条,比方说红色、蓝色和绿色。将一种颜色的所有条形指示的相对份额相加应等于每种颜色的 100%。 IE。如果蓝色表示 Accident_Severity = 2,蓝色条表示 1 月份为 10%,这意味着 1 月份发生的严重程度为 2 的所有事故中有 10%。

我通过以下操作 table 获得了这些数字:

pivot_rel <- df %>%
  select(month, Accident_Severity) %>%
  group_by(month) %>%
  table()

for (i in c(1,2,3)) {
  for (j in seq(1,12)) {
    pivot_rel[j,i] <- round(pivot_rel[j,i]/sum_severity[i],3)
  }
}

pivot_rel

pivot_rel

但是,我无法将对象与 ggplot 一起使用。尝试时我收到错误消息:“Fehler:data 必须是数据框,或其他可由 fortify() 强制的对象,而不是具有 class table 的 S3 对象”

我如何可视化这个 table 或者是否有更简单的方法来实现我想要实现的目标?非常感谢!

一个简单的解决方法是将 table 更改为可以与 ggplot 一起使用的数据框。

pivot_rel <- as.data.frame.matrix(pivot_rel) 

但是,您也可以退后一步,使用 count 而不是 table 来生成 monthAccident_Severity 的频率计数。

library(dplyr)

pivot_rel <- df %>% count(month, Accident_Severity) 

使用xtabs到table数据和colSums得到比例。然后,使用包 ggplot2scales,绘制图形。

library(ggplot2)
library(scales)

tbl <- xtabs( ~ Month + Accident_Severity, df1)
t(tbl)/colSums(tbl)
#                 Month
#Accident_Severity   1   4   7
#                1 0.0 1.0 0.0
#                2 0.5 0.0 0.5
#                3 1.0 0.0 0.0

as.data.frame(t(tbl)/colSums(tbl)) |> 
  ggplot(aes(factor(Month), Freq, fill = factor(Accident_Severity))) +
  geom_col(position = position_dodge()) +
  scale_fill_manual(values = c("red", "green", "blue")) +
  scale_y_continuous(labels = percent_format()) +
  xlab("Month") +
  guides(fill = guide_legend(title = "Accident Severity"))


数据

df1 <- read.table(text = "
ID  Month   Accident_Severity
1   01  3
2   01  2
3   04  1
4   07  2
", header = TRUE)

xtabs 和基础 barplot 上使用 proportions

proportions(xtabs( ~ Month + Accident_Severity, d), margin=2) |>
  as.data.frame() |>
  with(barplot(Freq ~ Accident_Severity + Month, beside=T, col=2:4,
               main='Relative Frequencies', 
               legend.text=sort(unique(d$Accident_Severity)),
               args.legend=list(title='Accident_Severity')))


数据:

  d <- read.table(header=T, text='
                ID  Month   Accident_Severity
1   01  3
2   01  2
3   04  1
4   07  2')