使用ggplot2绘制线段图报错:无适用于character类的rescale方法
ggplot2环境采样时间变化图错误修复与优化
问题背景
需要绘制环境采样随时间变化的结果图,要求:
- 横轴为采样部署/回收日期
- 纵轴高度对应PCR检测结果
Value - 线段宽度对应采样器的部署时长
提供的数据集如下:
Deploy Rertieve Value 1 2021-08-29 2021-08-31 341.6431 2 2021-08-31 2021-09-02 259.8241 3 2021-09-02 2021-09-05 558.5531 4 2021-09-05 2021-09-07 872.5043 5 2021-09-07 2021-09-09 6130.8452 6 2021-09-10 2021-09-12 2655.0765
运行原代码时出现错误:
Error in `geom_segment()`: ! Problem while converting geom to grob. ℹ Error occurred in the 1st layer. Caused by error in `UseMethod()`: ! no applicable method for 'rescale' applied to an object of class "character" Run `rlang::last_error()` to see where the error occurred.
错误原因
- 图形属性未使用映射函数:
geom_segment的x/xend/y/yend参数直接写了字符串,没有通过aes()关联数据列,ggplot将这些字符串当作字符型字面量处理,导致类型不匹配错误。 - 列名拼写错误:原代码中写了
"Deployment"和"Retrieve",但实际数据列名为Deploy和Rertieve(注意拼写差异)。
修复与优化代码
# 重建数据集 sampling.dat <- structure(list(Deploy = structure(c(18868, 18870, 18872, 18875, 18877, 18880), class = "Date"), Rertieve = structure(c(18870, 18872, 18875, 18877, 18879, 18882), class = "Date"), Value = c(341.6431298, 259.824122, 558.5530897, 872.5042542, 6130.845229, 2655.076504)), row.names = 1:6, class = "data.frame") # 计算部署时长(单位:天) sampling.dat <- sampling.dat %>% mutate(duration = as.numeric(Rertieve - Deploy)) # 绘制图形 Segment.plot <- ggplot(data = sampling.dat) + # 正确使用aes映射列名,同时将时长映射到线段宽度 geom_segment(aes(x = Deploy, y = Value, xend = Rertieve, yend = Value, size = duration), color = "#2c3e50") + # 优化日期轴显示 scale_x_date(date_labels = "%Y-%m-%d", date_breaks = "2 days") + # 设置线段宽度范围,避免过粗/过细 scale_size_continuous(range = c(1, 3)) + # 添加标签与主题 labs(x = "日期", y = "PCR检测值", size = "部署时长(天)") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) Segment.plot
关键修复点
- 所有关联数据列的图形属性(x、xend、y、yend、size)必须放入
aes()函数中,让ggplot识别为数据映射而非固定值 - 修正列名拼写错误,确保与数据框中的列名完全一致
- 通过
as.numeric(Rertieve - Deploy)计算部署时长,将其映射到size参数实现“线段宽度对应部署时长”的需求 - 添加轴标签、日期格式化和主题优化,提升图表可读性
内容的提问来源于stack exchange,提问作者Seth Goodnight
相关产品推荐
相关产品推荐

