geom_line 中各个破折号的交替颜色

jac*_*olg 7 r ggplot2

我想知道在 a 中是否geom_line可以使单行内的破折号的颜色交替(而不是行之间的颜色不同)。例如,如果我希望这条单线交替出现红色、绿色和蓝色,而不仅仅是红色。

library(tidyverse)

ggplot(tibble(x = 1:10, y = 1:10), aes(x, y)) +
    geom_line(linetype = "dashed", color = "red") # i'd like to say something like, color = c("red", "green", "blue") instead
Run Code Online (Sandbox Code Playgroud)

r2e*_*ans 8

par(lty=)虽然效率有点低,但关于 R (geom_line(linetype=) 共享)的一个鲜为人知的事情是它可以指定为开/关拉伸。从线路类型规格?par下:

 Line types can either be specified by giving an index into a small
 built-in table of line types (1 = solid, 2 = dashed, etc, see
 'lty' above) ...
Run Code Online (Sandbox Code Playgroud)

(这是大多数教程/howtos/plots倾向于使用的)

          ... or directly as the lengths of on/off stretches of
 line.  This is done with a string of an even number (up to eight)
 of characters, namely _non-zero_ (hexadecimal) digits which give
 the lengths in consecutive positions in the string.  For example,
 the string '"33"' specifies three units on followed by three off
 and '"3313"' specifies three units on followed by three off
 followed by one on and finally three off.  The 'units' here are
 (on most devices) proportional to 'lwd', and with 'lwd = 1' are in
 pixels or points or 1/96 inch.
Run Code Online (Sandbox Code Playgroud)

其他描述和示例可以在 中找到?ggplot2::aes_linetype_size_shape

所以有了你的dat,人们就可以做到

 Line types can either be specified by giving an index into a small
 built-in table of line types (1 = solid, 2 = dashed, etc, see
 'lty' above) ...
Run Code Online (Sandbox Code Playgroud)

要得到

在此输入图像描述

如果没有一个空格,我就无法让它工作:开/关延伸必须始终以“on”开始,并以“off”结束;因此,我找不到一个不(至少一次)在没有强加间隙的情况下以“on”结尾的模式。

为了进一步解释,由于我们总是必须以“on”开头,所以我以至少一个“on”像素开始所有三个;诀窍是使开头的“长”延伸成为绘制的最后一行,因此它会过度绘制其他线。

red:  R.......RRRR.
      1       -4--
       ---7---    1

grn:  G...GGGG.....
      1   -4--
       -3-    --5--

blu:  BBBB.........
      -4--
          ----9----
Run Code Online (Sandbox Code Playgroud)

这有一些优点:无论 怎样size=,它的缩放比例都是相同的。例如,省略size=,

在此输入图像描述

  • 很好的解决方案。对于那些稍后需要两种颜色的人,请设置一个 `linetype='131111'`,另一个 `linetype='111113'` (2认同)