# Draw blue and red lines alternatingly

Given an array of points, I want to draw blue and red lines alternatingly.

Let $$n\in\{0,1\}$$, and arr be an array of points $$\textrm{arr} = \{ \{x_1, y_1\}, \{x_2,y_2\}, \ldots, \{x_n, y_n\}\}.$$ If $$n=0$$, I draw a blue line from the origin to $$\{x_1, y_1\}$$, then a red line from $$\{x_1, y_1\}$$ to $$\{x_2, y_2\}$$, then a blue line from $$\{x_2, y_2\}$$ to $$\{x_3, y_3\}$$, until the last line from $$\{x_{n-1}, y_{n-1}\}$$ to $$\{x_{n}, y_{n}\}$$.

If $$n=1$$, the blue and red lines are reversed. I draw a red line from the origin to $$\{x_1, y_1\}$$, then a blue line from $$\{x_1, y_1\}$$ to $$\{x_2, y_2\}$$, then a red line from $$\{x_2, y_2\}$$ to $$\{x_3, y_3\}$$, until the last line from $$\{x_{n-1}, y_{n-1}\}$$ to $$\{x_{n}, y_{n}\}$$.

For example, if

n=0
arr = {{1,0}, {2,0}, {3,0}}


then the result is

How can I make a function F[n,arr] returns a Lines object that draws the above?

Note: I tried a clumsy approach

colors[n_] := If[Mod[n, 2] == 1, Red, Blue]
F[n_, arr_] := Block[ {res = {}, newarr = Join[{{0, 0}}, arr]},
For[i = 1; i <= Length[arr], i++,
Append[res, {colors[n + i], Line[newarr[[i]], newarr[[i + 1]]]}]];
res]


With the above n and arr, I get an empty list (that is not what I want).

• Please include what you have tried so far as Mathematica code. Thanks.
– Syed
Commented Apr 26, 2023 at 6:37
• @syed I added my trial. Thanks. Commented Apr 26, 2023 at 7:17

Clear["Global*"];
SeedRandom[123];
arr = Prepend[RandomReal[1, {20, 2}], {0, 0}];
t := Sequence @@@ MapIndexed[
{If[EvenQ[n + First@#2]
, Red, Blue], Line[#1]} &
, Partition[arr, 2, 1]];

GraphicsRow@Table[
Graphics[t
, Frame -> True
, AspectRatio -> Automatic
, Epilog -> {
Text[
Style[
ToString@StringForm["n = ", n]
, 18]
, {0.6, 0.9}]
}
]
, {n, {0, 1}}
]


• Thanks! I think this is the closest answer, since it returns a list of line objects. Commented Apr 30, 2023 at 1:16
listLinePlot[n_, data_, opts : OptionsPattern[]] := ListLinePlot[
Partition[data, 2, 1],
PlotStyle -> RotateLeft[{Blue, Red}, n],
opts ]


Examples:

SeedRandom[123];
arr = Prepend[{0, 0}] @ RandomReal[1, {20, 2}];

listLinePlot[0, arr, PlotLabel -> Style["n = 0", 20]]


listLinePlot[1, arr, PlotLabel -> Style["n = 1", 20]]


• Thanks for your answer! I slightly modified your code to incorporate the origin {0,0}. Commented Apr 30, 2023 at 1:09
theLines = Line /@
Partition[Table[{RandomReal[], RandomReal[]}, {20}], 2, 1];
Graphics[
Flatten@{{Red, #[[1]]}, {Blue, #[[2]]} } & /@ Partition[theLines, 2]]
`