2
$\begingroup$

I have this code and when I am using PlotRange (M.12.0.0.0) it gives me error

colorBar[arg_] := Blend[{Red, Green, Blue}, Rescale[arg, {-1, 1}]];
postE = Table[{x, 0.05 + Cos[x]^2, Cos[x]}, {x, 0, 30, 0.05}];
ListLinePlot[postE[[All, 1 ;; 2]], PlotRange -> {-1, 1}, 
 ColorFunction -> 
  Function[{x, y}, 
   colorBar[postE[[Position[postE[[All, 1]], x][[1, 1]], 3]]]], 
 ColorFunctionScaling -> False];  



Part::partw: Part 1 of {} does not exist.
Part::pkspec1: The expression {}[[1,1]] cannot be used as a part specification.
Part::pkspec1: The expression {}[[1,1]] cannot be used as a part specification.
Part::pkspec1: The expression {}[[1,1]] cannot be used as a part specification.
General::stop: Further output of Part::pkspec1 will be suppressed during this calculation.  

Evnthough I get the result correctly but why this is error appearing? If I remove PlotRange it works fine!!

$\endgroup$

1 Answer 1

3
$\begingroup$

In drawing the line, there are values of x that are not equal to any of the x values in postE. Consequently, use Nearest[postE[[All, 1]], x][[1]] rather than x in the ColorFunction

Clear["Global`*"]

colorBar[arg_] := Blend[{Red, Green, Blue}, Rescale[arg, {-1, 1}]];
postE = Table[{x, 0.05 + Cos[x]^2, Cos[x]}, {x, 0, 30, 0.05}];

ListLinePlot[Most /@ postE,
 PlotRange -> {-1, 1},
 ColorFunction :> 
  Function[{x, y}, 
   colorBar[postE[[Position[postE[[All, 1]], 
        Nearest[postE[[All, 1]], x][[1]]][[1, 1]], 3]]]],
 ColorFunctionScaling -> False]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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