You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一图表中绘制美国各州枪支背景核查的多条趋势线

解决方案:将所有州枪支背景核查趋势线绘制在同一图表

要实现多州趋势线同图展示并按州区分颜色,推荐用dplyr分组计算趋势,再结合ggplot2完成可视化,替代原循环绘制单图的逻辑。

步骤1:数据预处理与趋势计算

先对每个州的时间序列进行分解,提取趋势项并整合到统一数据框:

library(tidyverse)
library(lubridate)
library(ggplot2)

# 读取数据集(若未加载)
firearm <- read_csv("https://raw.githubusercontent.com/BuzzFeedNews/nics-firearm-background-checks/master/data/nics-firearm-background-checks.csv")

dat <- firearm %>% 
  mutate(date = ymd(paste(month, "01"))) %>%
  select(date, state, totals) %>%
  filter(complete.cases(.)) %>%
  arrange(date) 

# 分组计算每个州的趋势项
trend_data <- dat %>%
  group_by(state) %>%
  mutate(
    # 创建对应州的时间序列对象
    ts_obj = list(ts(totals, start = c(min(year(date)), month(min(date))), frequency = 12)),
    # 分解时间序列并提取趋势值
    trend = as.numeric(decompose(ts_obj[[1]])$trend)
  ) %>%
  ungroup() %>%
  # 移除趋势分解后产生的首尾NA值
  filter(!is.na(trend))

步骤2:用ggplot2绘制同图趋势线

通过color = state映射实现州与颜色的关联,绘制所有州的趋势线:

ggplot(trend_data, aes(x = date, y = trend, color = state)) +
  geom_line(alpha = 0.7) + # 调整透明度,避免线条重叠过密
  labs(
    title = "美国各州枪支背景核查趋势变化",
    x = "日期",
    y = "趋势值",
    color = "州"
  ) +
  theme_minimal() +
  theme(
    legend.position = "bottom", # 图例移至底部,节省纵向空间
    plot.title = element_text(hjust = 0.5) # 标题居中
  )

优化建议(可选)

如果所有州的线条过于杂乱,可筛选部分重点州展示,比如人口较多的州:

# 筛选目标州
top_states <- c("California", "Texas", "Florida", "New York", "Pennsylvania")

trend_data %>%
  filter(state %in% top_states) %>%
  ggplot(aes(x = date, y = trend, color = state)) +
  geom_line(linewidth = 1) +
  labs(title = "美国人口大州枪支背景核查趋势变化", x = "日期", y = "趋势值", color = "州") +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5))

内容的提问来源于stack exchange,提问作者Syed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 12:37:26