求助:使用ggplot绘制两党演讲频次随时间变化折线图
演讲频次随时间变化折线图绘制问题
样本数据集
myDataSet1 <- as.data.frame(cbind ("dates" = c("13-Jan", "15-Jan", "20-Jun", "13-May", "19-Dec"), "Party" = c("Republican", "Democrat", "Republican", "Democrat", "Democrat"), "Speeches" = c("2", "6", "9", "3", "6") ) )
首次尝试与报错
尝试代码:
ggplot(data = myDataSet1, mapping = aes(x = dates, y = Speeches, color = Party)) + geom_line()
报错信息:
error: geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
后续修改与新报错
修改后的代码:
myDataSet1 %>% mutate(Speeches = as.integer(as.character(Speeches)), dates = as.Date(paste0(dates, "-2022"), "%y-%b-%d")) %>% ggplot(aes(x = dates, y = court_rhetoric, color = Party)) + geom_line() + scale_x_date(date_labels = "%y-%b")
报错信息:
Error in
fortify():
!datamust be a data frame, or other object coercible byfortify(), not an S3 object with class uneval.
Did you accidentally passaes()to thedataargument?
另一个报错:
Error: Invalid input: date_trans works with objects of class Date only
问题分析与解决方案
核心问题
- 原始数据中
dates为字符型,未转换为标准日期格式;Speeches为字符型而非数值型,ggplot无法识别数据的连续关系 - 修改代码时出现笔误:将
y = Speeches误写为y = court_rhetoric,导致数据映射错误 - 日期转换逻辑错误:原日期格式为
yy-mmm,错误添加了固定年份2022,而非补全日份,导致日期解析失败
正确代码
library(tidyverse) # 清洗数据:转换类型、修正日期格式、排序 myDataSet1_cleaned <- myDataSet1 %>% mutate( # 将演讲次数转为整数型 Speeches = as.integer(Speeches), # 补全日份为当月1号,将yy-mmm转为标准Date格式 dates = as.Date(paste0(dates, "-01"), format = "%y-%b-%d") ) %>% # 按日期排序,保证折线顺序正确 arrange(dates) # 绘制折线图 ggplot(myDataSet1_cleaned, aes(x = dates, y = Speeches, color = Party, group = Party)) + geom_line(linewidth = 1) + # 设置x轴日期显示为yy-mmm格式 scale_x_date(date_labels = "%y-%b") + labs(title = "演讲频次随时间变化", x = "时间", y = "演讲次数") + theme_minimal()
代码说明
mutate部分:修正数据类型,补全日份后将字符型日期转为标准Date格式,让ggplot能识别时间顺序arrange(dates):按日期排序,避免折线出现乱序跳跃aes中指定group = Party:确保ggplot按政党分组连线,即使部分时间点某政党无数据(若后续有缺失值,可通过complete函数补全)scale_x_date:自定义x轴显示格式,匹配需求的yy-mmm
内容的提问来源于stack exchange,提问作者ertey
相关产品推荐
相关产品推荐

