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

使用ggplot的geom_line绘制时间序列时第二个数据集显示异常如何解决

R语言时间序列折线图绘制异常修复方案

问题背景

基于R内置economics数据集绘制美国失业率时间序列图的代码运行正常:

library(tidyverse)
library(dplyr)
data("economics")

economics %>% 
  ggplot(aes(date, unemploy, pop)) + 
  geom_line(col = "maroon") + 
  xlab("Year") + 
  ylab("U.S. Unemployment Rate")

对应正常绘图结果:
Unemployment Plot

使用美国财政部公开的「精确到美分的债务」数据集时绘图结果不符合预期,所用原始代码如下:

library(tidyverse)
library(dplyr)
data(debt)

debt <- read.csv("C:##path here to the data")

debt %>%
  filter(Calendar.Month.Number==12 & Calendar.Day.Number==31) %>% 
  ggplot(aes(Calendar.Year, Debt.Held.by.the.Public)) +
  geom_line(col = "blue")

异常绘图结果:
Debt plot

调整方案

需要做两处核心修改:

  • 删除冗余代码data(debt):data()函数用于加载R内置数据集,你的债务数据为本地csv文件,该行代码会报错或者覆盖你读取的本地数据,直接删除即可。
  • 转换债务字段格式:csv读取的Debt.Held.by.the.Public字段默认是带美元符号、千位分隔逗号的字符类型,ggplot无法识别为数值指标,需要先清洗转换为数值格式,也可以拼接年月日为完整日期字段作为x轴,时间粒度比单独使用年份更准确。

修正后的参考代码如下:

library(tidyverse)
library(dplyr)

# 读取本地债务数据
debt <- read.csv("C:##替换为你本地的文件存储路径")

debt %>%
  # 数据预处理:清洗债务字段转数值,可选拼接完整日期
  mutate(Debt.Held.by.the.Public = as.numeric(gsub("[$,]", "", Debt.Held.by.the.Public)),
         record_date = as.Date(paste(Calendar.Year, Calendar.Month.Number, Calendar.Day.Number, sep = "-"))) %>%
  # 仅保留每年年末数据的过滤逻辑可以根据需求保留或删除
  filter(Calendar.Month.Number==12 & Calendar.Day.Number==31) %>% 
  ggplot(aes(x = record_date, y = Debt.Held.by.the.Public)) +
  geom_line(col = "blue") +
  xlab("年份") +
  ylab("公众持有债务规模")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:48:02