求助:R中ggplot生成的对象为何变为列表而非绘图?
ggplot创建的对象被识别为列表而非绘图对象
问题描述
执行以下代码后,unemp_jolts_plot被识别为列表而非绘图对象,尝试print()和view()函数也无法解决问题:
unemp_jolts_plot <- ggplot() + geom_line(data = new_melt.df, size=1.15, aes(x=date, y=value, color = variable)) + labs(title= "Unemployment and Job Openings", x= NULL, y=NULL, caption = "Source: BLS")+ theme_bw() + scale_x_date(labels = date_format("%Y"), breaks='2 years',limits = c(min, max)) theme(legend.position = c(.50, .97), legend.justification = c(0, 1), legend.text = element_text(size=14),legend.background=element_blank())
问题截图:
问题原因与解决办法
- 核心问题:代码中
scale_x_date()语句末尾缺少+号,导致后续的theme()没有被整合到ggplot绘图对象链中,反而被当作独立语句执行,最终引发unemp_jolts_plot的对象类型异常。 - 修复后的代码:在
scale_x_date()行末尾添加+号,将theme()连接到绘图对象上:
unemp_jolts_plot <- ggplot() + geom_line(data = new_melt.df, size=1.15, aes(x=date, y=value, color = variable)) + labs(title= "Unemployment and Job Openings", x= NULL, y=NULL, caption = "Source: BLS")+ theme_bw() + scale_x_date(labels = date_format("%Y"), breaks='2 years',limits = c(min, max)) + theme(legend.position = c(.50, .97), legend.justification = c(0, 1), legend.text = element_text(size=14),legend.background=element_blank())
ggplot2构建绘图时,所有图层、主题、标度等元素必须通过+号串联成一个完整的ggplot对象,缺少+会导致元素无法整合,进而引发对象类型异常。
内容的提问来源于stack exchange,提问作者user22453877
相关产品推荐
相关产品推荐

