performance tuning - Plotting the components of a function that returns a list in different colors without redundant evaluations of the function
I have a function f
which takes a number as input, and returns a list of numbers (the length of the list is constant). f
is hard to calculate (each evaluation takes a long time).
I want to plot the different components of f
in different colors.
If I use this command:
Plot[f[x], {x, -2, 2}]
all the lines are drawn in the same color.
If I use this command:
Plot[{f[x][[1]], f[x][[2]], f[x][[3]]}, {x, -2, 2}]
(assuming the list has three components) the lines are drawn in different colors, but the function is called three times the necessary amount.
Note that this is a numeric function, it cannot be evaluated with a symbolic argument (i.e. the function definition begins with f[x_Real]:=
), so there is no use in using Evaluate
like in this question.
Answer
At risk of stating the obvious, if you are willing to give up the adaptive sampling, exclusions, etc. of Plot
you could use ListLinePlot
:
f[x_?NumericQ] := x + Mod[x, {1, 2, 3}]
ListLinePlot[Transpose@Table[f[x], {x, 0, 10, 0.01}], PlotStyle -> Thick]
Better I think is to restyle the Graphics
data produced by plot, as Heike did for Plotting piecewise function with distinct colors in each section and which I refactored in my answer. Applied here:
Module[{i = 1},
Plot[f[x], {x, 0, 10}, PlotStyle -> Thick] /.
x_Line :> {ColorData[1][i++], x}
]
Even nicer is Simon Woods' method which styles the plot while it is created, posted in answer to:
Also useful and very interesting is the solution by wxffles in the follow-up question:
Comments
Post a Comment