4
$\begingroup$

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: enter image description here

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.

$\endgroup$
8
$\begingroup$

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
]

enter image description here

$\endgroup$
3
  • $\begingroup$ May I ask how to use another color function? For example the Hue or Opacity such that I can change the color freely? $\endgroup$
    – Xiaoyu Liu
    Jun 29 '21 at 22:18
  • $\begingroup$ @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. $\endgroup$ Jun 30 '21 at 2:46
  • 1
    $\begingroup$ @ca-trevillian Oh, I got it. Hue does not accept list. Hue/@data[[All,3]] is going to work. Thank you anyway. $\endgroup$
    – Xiaoyu Liu
    Jun 30 '21 at 3:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.