position <- (SCATGRAPH$position)\nspecies <- (SCATGRAPH$species)\nvalue <- (SCATGRAPH$value)\nhabitat <- (SCATGRAPH$habitat)\ndf <- data.frame(position,species,value,habitat)\nRun Code Online (Sandbox Code Playgroud)\nggplot(data=df, aes(x=habitat, y=value, group=species, colour=species, linetype=position)) + geom_line() + geom_point()\nRun Code Online (Sandbox Code Playgroud)\n上面没有生成图表,但引出了以下消息:
\nError in `geom_line()`:\n! Problem while converting geom to grob.\n\xe2\x84\xb9 Error occurred in the 1st layer.\nCaused by error in `draw_panel()`:\n! `geom_line()` can\'t have varying colour, linewidth, and/or\n alpha along the line when linetype isn\'t solid\nRun `rlang::last_error()` to see where the error occurred.\nRun Code Online (Sandbox Code Playgroud)\nrlang::last_error()信息如下
\nBacktrace:\n 1. base (local) `<fn>`(x)\n 2. ggplot2:::print.ggplot(x)\n 4. ggplot2:::ggplot_gtable.ggplot_built(data)\n 5. ggplot2:::by_layer(...)\n 12. ggplot2 (local) f(l = layers[[i]], d = data[[i]])\n 13. l$draw_geom(d, layout)\n 14. ggplot2 (local) draw_geom(..., self = self)\n 15. self$geom$draw_layer(...)\n 16. ggplot2 (local) draw_layer(..., self = self)\n 17. base::lapply(...)\n 18. ggplot2 (local) FUN(X[[i]], ...)\n 20. self$draw_panel(data, panel_params, coord, na.rm = FALSE)\n 21. ggplot2 (local) draw_panel(..., self = self)\nRun Code Online (Sandbox Code Playgroud)\n当我尝试仅按一种因素(颜色或线型)进行分组时,它的工作原理与预期完全一致
\nggplot(data=df, aes(x=habitat, y=value, group=species, colour=species))+ geom_line() \nRun Code Online (Sandbox Code Playgroud)\n\n当将“颜色”切换为“线型”时,等效代码也适用,如果将“物种”切换为“位置”(我的其他两类变量 - 我想与线型关联),则同样有效。
\n似乎有很多方法可以向 R 表达此请求。单独使用 geom_line(aes(linetype=position)) 或与上面的问题语法结合使用不会改善结果,也不会像其他帖子中提到的那样添加 scale_linetype_manual 命令。使用 Factor() 将“物种”或“位置”转换为因子也不起作用。
\n编辑:这是我的数据
\nstructure(list(habitat = structure(c(1L, 1L, 2L, 2L, 3L, 3L, \n4L, 4L, 1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), levels = c("Upland interior", \n"Upland edge", "Peatland edge", "Peatland interior"), class = "factor"), \n position = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, \n 1L, 2L, 1L, 2L, 1L, 2L, 1L), levels = c("On", "Off"), class = "factor"), \n species = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, \n 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c("Deer", "Moose"), class = "factor"), \n value = c(0.428571429, 0.31372549, 0.315789474, 0.315789474, \n 0.263157895, 0, 0.166666667, 0, 0.285714286, 0.196078431, \n 0, 0.263157895, 0.052631579, 0.157894737, 0, 0.15)), row.names = c(NA, \n-16L), class = "data.frame")\nRun Code Online (Sandbox Code Playgroud)\n
一些 ggplot2 的几何图形(如geom_line)对于每一系列观察结果只有一种颜色、线宽、alpha 等,这些观察结果应该美观地分组在一起。默认情况下,ggplot2 使用一些启发式方法来确定应将哪些观察结果分组在一起。美学group允许我们明确地指定这一点。https://ggplot2.tidyverse.org/reference/aes_group_order.html
就您而言,您的系列以它们species和它们的组合来区分position。为了对每个组合进行分组,我们可以使用group = interaction(species, position). (我们还可以使用paste(species, position)- 任何为每个组合提供不同值的东西。)
(有时会出现一个单独但相关的问题,即如何描绘具有不同美学的单个系列。为此,geom_segment和ggforce::geom_link是两种很好的方法。)