# How to use ListLinePlot to plot a multicolored line, where the colors are given by an array?

I have a 2D dataset with three columns. The first two columns are x and y, the third one is z. I want to plot a line with the colors specified by the z data.

Here is an ideal example, the only problem is that my dataset is not generated from a simple function.

data = Table[{x, Sin[x], Cos[x]}, {x, Range[-3.14, 3.14, 0.2]}]


I want to get a plot like this:

PS: This picture is generated by

ListLinePlot[Table[{x, Sin[x]}, {x, Range[-\[Pi], \[Pi], 0.2]}],
ColorFunction -> Function[{x, y}, Cos[x]], ColorFunctionScaling -> False]


But in reality I don't have a function z(x,y).

One way I tried is to find the index of {x,y}, but sometimes it fails. I hope there is a better way to solve this.

Just use Graphics directly instead of having ListLinePlot construct the Graphics object for you:

data = Table[{x, Sin[x], Cos[x]}, {x, Range[-3.14, 3.14, 0.2]}];
Graphics[
{Line[data[[All, ;;2]], VertexColors -> data[[All,3]]]},
Axes->True,
AspectRatio->1/GoldenRatio
]


• May I ask how to use another color function? For example the Hue or Opacity such that I can change the color freely? Jun 29 '21 at 22:18
• @Xiaoyu Liu wrap the input to VertexColors in whatever you want to use; i.e., something like VertexColors->Hue[data[[All,3]]] should work, with modifications as appropriate for your desired use case. Jun 30 '21 at 2:46
• @ca-trevillian Oh, I got it. Hue does not accept list. Hue/@data[[All,3]] is going to work. Thank you anyway. Jun 30 '21 at 3:07