4

Suppose I have a simple function like $\cos(kx)$, and I am plotting a number of such functions with different values for $k$ as in:

Plot[Table[Cos[k x], {k, 1, 4, 1}], {x, 0, π}]

How can I color them depending on the $k$ parameter without setting it manually myself, as in:

Plot[Evaluate[Table[Cos[k x], {k, 1, 4, 1}]], {x, 0, π},
  PlotStyle -> Table[Blend[{Blue, Red}, k/4], {k, 1, 4, 1}]]

?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
  • Plot[Evaluate[Table[Cos[k x], {k, 1, 4, 1}]], {x, 0, \[Pi]}] automatically colors them differently for each k. Is that what you mean? If you want each plot colored specifically but you don't want to specify the colors "manually," then either I don't understand what you want or it cannot be accomplished. – Michael E2 Sep 25 '17 at 23:36
  • 3
    Maybe this?: Plot[Evaluate[Table[Style[Cos[k x], Blend[{Blue, Red}, k/4]], {k, 1, 4, 1}]], {x, 0, \[Pi]}] – Michael E2 Sep 25 '17 at 23:38
  • @MichaelE2 Yes, that's exactly what I wanted! You got it! I'm gonna study that syntax. – Pablo Fernández Esteberena Sep 25 '17 at 23:40
  • 1
    I was about to suggest Style as @Michael just posted; see (8191) – Mr.Wizard Sep 25 '17 at 23:42
  • @Michael Do you think this is close enough to 8191 to be marked as a duplicate? – Mr.Wizard Sep 25 '17 at 23:51
  • @Mr.Wizard That's what I was trying to figure out. I'm generally inclined to say that if the same methods/approaches work for both questions, then they are duplicates. That criterion seems to apply here. OTOH, the particular differences of such questions occasionally lead community members to disagree with me. – Michael E2 Sep 26 '17 at 00:02

2 Answers2

6

This seems to be the desired form:

Plot[
 Evaluate[Table[Style[Cos[k x], Blend[{Blue, Red}, k/4]], {k, 1, 4, 1}]],
 {x, 0, π}]

Mathematica graphics

Michael E2
  • 235,386
  • 17
  • 334
  • 747
1

It may help to use PlotLabels and PlotLegends options to identify the plotted functions.

Plot[Evaluate[
Table[Style[Cos[k x], Blend[{Blue, Red}, k/4]], {k, 1, 4, 1}]], {x, 0, π}, 
PlotLabels -> Placed[Automatic, {Above, Below, After, Below}], 
PlotLegends -> "Expressions"]
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Syd Geraghty
  • 134
  • 5