2
$\begingroup$

For example, how can I extract the black, red, blue parts of a line, and another green line in the diagram below as four separate data sets?

Here is my attempt and code, but it hasn't been successful.

I would appreciate any help, thank you!

SetOptions[Plot, ColorFunctionScaling -> False];

colorfun = 
  Function[{x, y}, If[Cos[x] > 0, Red, If[x y < 0, Blue, Black]]];
tend = 10;
fig = Show[{Plot[Sin[Cos[t^2]], {t, 0, tend}, 
    ColorFunction -> colorfun], 
   Plot[Cos[Sin[t^2]], {t, 0, tend}, 
    PlotStyle -> {Thin, Green, Dashed}]}, PlotRange -> All]

dat = Cases[InputForm@fig, Line[x_] :> x, ∞];

ListPlot[Evaluate@dat]

colored lines of parts of a line

$\endgroup$

1 Answer 1

6
$\begingroup$

You're using InputForm and Evaluate blindly. InputForm is only for displaying the inputform in frontend, it won't influence the FullForm of code. Evaluate is only for functions with attribute adjusting the evaluation order e.g. HoldAll, HoldFirst, etc., ListPlot doesn't have such attributes, so Evaluate won't have any effect. These are not causing problem in your code, though.

The root of the problem is, the colors of line segments colored by ColorFunction option are not specified by the Graphics[{color, Line[...]},...] syntax, it's specified by VertexColors option of a GraphicsComplex[...] expression. (This is not too hard to notice by observing the fig by pressing Ctrl+Shift+i, or using InputForm, or using ShortInputForm. )

So a possible solution is:

dat = Cases[fig, GraphicsComplex[a_, __] :> a, Infinity][[1]];

color = Cases[fig, (VertexColors -> a_List) :> a, ∞][[1]];

lst = dat[[Flatten@Position[color, #]]] & /@ {Black, Blue, Red};

(* Find out those not colored by VertexColors: *)
datrest = 
  Complement[#, dat] & /@ Cases[fig, Line[a_] :> a, ∞] // 
   DeleteCases[{}];

ListPlot[Join[lst, datrest], PlotStyle -> {Black, Blue, Red, Green}]

enter image description here

$\endgroup$
3
  • $\begingroup$ Thanks. Your explanation is so clear as always. Perfect! Have a nice day :) $\endgroup$
    – xinxin guo
    Commented Oct 23 at 7:24
  • $\begingroup$ @xinxinguo You should really put a bit more effort in understanding the core language… I tried explaining Evaluate and InputForm a bit more in the answer, have a look. $\endgroup$
    – xzczd
    Commented Oct 24 at 3:21
  • $\begingroup$ You're absolutely right, I will reinforce my study of the basics of Mathematica. Thanks for your advice! :) $\endgroup$
    – xinxin guo
    Commented Oct 25 at 6:34

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.