使用ggplot2同时按颜色和线型分组绘图触发报错的问题
ggplot2多分组折线图绘制报错问题
- 从CSV列构建DataFrame,检查后数据无异常:
position <- (SCATGRAPH$position) species <- (SCATGRAPH$species) value <- (SCATGRAPH$value) habitat <- (SCATGRAPH$habitat) df <- data.frame(position,species,value,habitat)
- 尝试绘制包含4条线的折线图,通过颜色区分
species、线型区分position,代码如下:
ggplot(data=df, aes(x=habitat, y=value, group=species, colour=species, linetype=position)) + geom_line() + geom_point()
运行代码后未生成图表,触发报错:
Error in
geom_line():
! Problem while converting geom to grob.
ℹ Error occurred in the 1st layer.
Caused by error indraw_panel():
!geom_line()can't have varying colour, linewidth, and/or
alpha along the line when linetype isn't solid
Runrlang::last_error()to see where the error occurred.
执行rlang::last_error()得到回溯信息:
Backtrace: 1. base (local) `<fn>`(x) 2. ggplot2:::print.ggplot(x) 4. ggplot2:::ggplot_gtable.ggplot_built(data) 5. ggplot2:::by_layer(...) 12. ggplot2 (local) f(l = layers[[i]], d = data[[i]]) 13. l$draw_geom(d, layout) 14. ggplot2 (local) draw_geom(..., self = self) 15. self$geom$draw_layer(...) 16. ggplot2 (local) draw_layer(..., self = self) 17. base::lapply(...) 18. ggplot2 (local) FUN(X[[i]], ...) 20. self$draw_panel(data, panel_params, coord, na.rm = FALSE) 21. ggplot2 (local) draw_panel(..., self = self)
- 仅按单一因子(颜色或线型)分组时,代码可正常运行,示例:
ggplot(data=df, aes(x=habitat, y=value, group=species, colour=species))+ geom_line()
将colour替换为linetype,或把species替换为position,对应代码也能正常执行。
- 已尝试多种解决方案:单独在
geom_line中设置aes(linetype=position)、调整语法结构、添加scale_linetype_manual命令、将species或position转为因子,均无法解决报错问题。
补充数据集:
structure(list(habitat = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), levels = c("Upland interior", "Upland edge", "Peatland edge", "Peatland interior"), class = "factor"), position = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L), levels = c("On", "Off"), class = "factor"), species = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c("Deer", "Moose"), class = "factor"), value = c(0.428571429, 0.31372549, 0.315789474, 0.315789474, 0.263157895, 0, 0.166666667, 0, 0.285714286, 0.196078431, 0, 0.263157895, 0.052631579, 0.157894737, 0, 0.15)), row.names = c(NA, -16L), class = "data.frame")
内容的提问来源于stack exchange,提问作者Joel Plaskett
相关产品推荐
相关产品推荐

