R语言绘制可变宽度柱状图时调用自定义函数返回对象报未找到错误
可变宽度柱状图坐标绑定修正方案
报错原因
在geom_rect()的aes()中直接引用s和e时触发“对象s未找到”提示,核心原因是函数返回的坐标值仅作为独立变量存在,没有被写入作为ggplot数据源的df数据框中,ggplot仅能识别绑定数据源内的列字段。
修正操作步骤
- 完成自定义函数
widths_to_starts_ends的定义 - 调用函数传入
df中的宽度列,获取返回的坐标列表 - 将列表中的起点、终点坐标作为新列赋值给
df,完成数据源字段绑定 - 在绘图映射中使用新列名引用对应坐标
可直接运行的完整代码
# 定义自定义坐标计算函数 widths_to_starts_ends <- function(widths){ widths <- widths[widths != 0] pos_widths <- widths[widths > 0] neg_widths <- widths[widths < 0] pos_ends <- cumsum(pos_widths) pos_starts <- cumsum(pos_widths) - pos_widths neg_widths <- abs(neg_widths) neg_starts <- cumsum(neg_widths) neg_ends <- cumsum(neg_widths) - neg_widths neg_starts <- (-1)*neg_starts neg_ends <- (-1)*neg_ends return( list(s = c(neg_ends, pos_starts), e = c(neg_starts, pos_ends)) ) } # 调用函数计算所有步骤的x轴坐标 coord_result <- widths_to_starts_ends(df$width) # 将坐标写入df作为绘图可用的字段 df$xmin <- coord_result$s df$xmax <- coord_result$e # 绘制可变宽度柱状图 library(ggplot2) p <- ggplot(df, aes(ymin = 0)) p1 <- p + geom_rect(aes(xmin = xmin, xmax = xmax, ymax = Variability, fill = Steps)) p1
潜在问题提示
当前的自定义函数存在两个易引发结果错误的逻辑缺陷:
- 函数会自动过滤宽度为0的步骤,导致返回的坐标长度与原
df的行数不匹配,触发列长度不一致报错 - 函数将所有负宽度步骤的坐标统一排列在序列前部、所有正宽度步骤的坐标统一排列在后部,未保留步骤的原始排列顺序。若负宽度步骤出现在序列中间,会出现坐标与对应步骤完全错配的问题。
内容的提问来源于stack exchange,提问作者Jeiran
相关产品推荐
相关产品推荐

