2
$\begingroup$

I have a function which returns a vector, like this:

f[x_] := With[{u = MixedFractionParts[x]}, UnitVector[4, u[[1]]] u[[2]]]

and would like to plot it:

Plot[f[x], {x, 1, 4}]

This gives me a plot where all lines are plotted in the default blue color, however I would like each of them to be plotted in a different color. Normally I would use evaluate, e.g. Plot[f[x], {x, 1, 4}, Evaluated->True], but that doesn't work and gives errors like "Part 2 of MixedFractionParts[x] does not exist".

How can I plot this function with a different color per dimension?

$\endgroup$

2 Answers 2

4
$\begingroup$

Edit

Since Plot have the attribute HoldAll,

Attributes[Plot]
(* {HoldAll, Protected, ReadProtected} *)

Plot can't see the structure of f[x] until give the values of x so Evaluate can not work.( Evaluate[f[x]] get error).

By now,we have to tell Plot the structure of f[x], that is what the original way which use Part.

Here we gave another approach.

Clear[n, f, plot, colors];
n = 10;
f[x_] := 
  With[{u = MixedFractionParts[x]}, UnitVector[n, u[[1]]] u[[2]]];
plot = Plot[f[x], {x, 1, n + 1}];
colors = ColorData["Rainbow"] /@ Subdivide[0, 1, n];
Block[{e = 0}, plot /. Line[pts_] :> {colors[[++e]], Line[pts]}]

enter image description here

Original

Plot[{f[x][[1]], f[x][[2]], f[x][[3]], f[x][[4]]}, {x, 1, 4}]

enter image description here

$\endgroup$
1
  • $\begingroup$ I was hoping for an approach which works for various n.. $\endgroup$
    – Danvil
    Sep 7, 2022 at 4:01
3
$\begingroup$
Clear["Global`*"]

f[x_] := 
 With[{u = MixedFractionParts[x]}, UnitVector[4, u[[1]]] u[[2]]]

ListLinePlot[
 Transpose@Table[f[x], {x, 1, 4, 0.01}],
 DataRange -> {1, 4},
 PlotRange -> All]

enter image description here

EDIT: For variable n

Clear["Global`*"]

f[x_, n_Integer?Positive] := 
 With[{u = MixedFractionParts[x]}, UnitVector[n, u[[1]]] u[[2]]]

n = 6;

ListLinePlot[
 Transpose[f[#, n] & /@ Range[1, n, 0.01]],
 DataRange -> {1, n}]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thank you! So Plot is not able to do this? $\endgroup$
    – Danvil
    Sep 7, 2022 at 6:39

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.