0

I stumbled upon some odd behaviour in Plot that does not really make sense to me. I stumbled on it with a more complicated scenario, but a distilled demo is below.

If I make some data

data = {Sin[x], Sin[2 x], Sin[3 x]};

Then plot it using this code, the lines have different colours

Plot[data, {x, 0, 2 Pi}]

If I plot the same lines using Part as in this code, the lines are all the same colour

Plot[data[[All]], {x, 0, 2 Pi}]

If I use Part but prior to create a new variable

data2 = data[[All]]

Then plot

Plot[data2, {x, 0, 2 Pi}]

The lines regain their different colours.

Obviously Mathemtica is treating the second example as different somehow. But to me, this seems rather unintuitive. Is there a reason for this behaviour and is it intended? If intended, why is it there / what is it useful for?

flyingmind
  • 489
  • 2
  • 10
  • 3
    This is due to the HoldAll attribute of Plot. Look at what happens when you evaluate Plot[data[[All]] // Evaluate, {x, 0, 2 Pi}]. (See this as well.) – J. M.'s missing motivation May 26 '22 at 12:50
  • Ah, thanks I missed this, indeed my original use case was with Table. So basically Plot treats the List/Table as a single "chunk" and applies the same colour to that "chunk". But internally it must recognise all of elements of the List/Table, else it would not plot multiple lines. So it is "colouring" prior to "evaluating"? – flyingmind May 26 '22 at 13:23
  • Plot can color things is it knows how long the list of expressions is. If the first argument is Part[data,All] and it is not evaluated, the list length is unknown. – Craig Carter May 26 '22 at 14:21
  • I am still a little confused. One one level "Plot" does not know the length of the list (for colouring). But on another level Plot knows very well the length of the list as it plots multiple lines. – flyingmind May 26 '22 at 14:44
  • 1
    Plot can determine the length of the list after evaluation. I am not sure why it doesn’t check after evaluation and determine the length—perhaps there are some cases where that is impossible, although I can’t think of one. It’s now a reflex: if I don’t see colors, I force evaluation. I tend to use: With[{list = Table[x^n,{n,1,10}]},Plot[list,{x,0,1}] – Craig Carter May 26 '22 at 15:40
  • If someone would like to post an answer I would be happy to accept it. J.M.? you were first to answer. Thanks both for the help and advice. – flyingmind May 27 '22 at 08:57

0 Answers0