如何在R中绘制区分致命/非致命事件的年份频率直方图?
解决方案:区分致命/非致命事件的年度直方图
Base R 实现方法
堆叠柱状图(更清晰展示年度总量拆分)
先按年份和事件类型统计频次,再绘制堆叠图:
# 读取数据 Confirmed_Unprovoked_Attacks_ALL <- read.csv("/path to csv/.csv") # 将outcome转为因子,赋予明确标签 Confirmed_Unprovoked_Attacks_ALL$outcome <- factor( Confirmed_Unprovoked_Attacks_ALL$outcome, levels = c(1,2), labels = c("致命", "非致命") ) # 按年份+事件类型分组统计数量 attack_counts <- table( Confirmed_Unprovoked_Attacks_ALL$year, Confirmed_Unprovoked_Attacks_ALL$outcome ) # 绘制堆叠柱状图 barplot( attack_counts, main = '确认的无端袭击事件', ylab = '袭击数量', xlab = '年份', col = c("#e74c3c", "#3498db"), # 自定义区分颜色 legend.text = colnames(attack_counts), args.legend = list(x = "topright") )
重叠半透明直方图
如果想保留直方图的分布感,可叠加半透明图层:
# 提取两类事件的年份数据 fatal_years <- Confirmed_Unprovoked_Attacks_ALL$year[Confirmed_Unprovoked_Attacks_ALL$outcome == 1] nonfatal_years <- Confirmed_Unprovoked_Attacks_ALL$year[Confirmed_Unprovoked_Attacks_ALL$outcome == 2] # 先绘制致命事件直方图(半透明) hist( fatal_years, main = '确认的无端袭击事件', ylab = '袭击数量', xlab = '年份', breaks = 100, xlim = c(1850,2050), col = rgb(231,76,60, maxColorValue = 255, alpha = 80) ) # 叠加非致命事件直方图 hist( nonfatal_years, breaks = 100, xlim = c(1850,2050), col = rgb(52,152,219, maxColorValue = 255, alpha = 80), add = TRUE ) # 添加图例 legend( "topright", legend = c("致命", "非致命"), fill = c( rgb(231,76,60, maxColorValue = 255, alpha = 80), rgb(52,152,219, maxColorValue = 255, alpha = 80) ) )
ggplot2 实现方法
ggplot2对分组可视化支持更简洁,可灵活切换堆叠、并列、重叠模式:
library(ggplot2) # 读取数据并处理标签 Confirmed_Unprovoked_Attacks_ALL <- read.csv("/path to csv/.csv") Confirmed_Unprovoked_Attacks_ALL$outcome <- factor( Confirmed_Unprovoked_Attacks_ALL$outcome, levels = c(1,2), labels = c("致命", "非致命") ) # 堆叠直方图(默认模式) ggplot(Confirmed_Unprovoked_Attacks_ALL, aes(x = year, fill = outcome)) + geom_histogram(breaks = seq(1850, 2050, length.out = 101)) + labs(title = '确认的无端袭击事件', y = '袭击数量', x = '年份') + scale_x_continuous(limits = c(1850, 2050)) + scale_fill_manual(values = c("#e74c3c", "#3498db")) + theme_minimal() # 若要重叠直方图,修改position参数并设置透明度 ggplot(Confirmed_Unprovoked_Attacks_ALL, aes(x = year, fill = outcome)) + geom_histogram( breaks = seq(1850, 2050, length.out = 101), position = "identity", alpha = 0.5 ) + labs(title = '确认的无端袭击事件', y = '袭击数量', x = '年份') + scale_x_continuous(limits = c(1850, 2050)) + scale_fill_manual(values = c("#e74c3c", "#3498db")) + theme_minimal()
内容的提问来源于stack exchange,提问作者elasmojoe757
相关产品推荐
相关产品推荐

