1
$\begingroup$

I'm trying to get legends for different initial values for the solutions to an ode to show up. I currently have

g[t_] = Piecewise[{{2, t <= 3}, {0, t > 3}}];
ode = R*c*v'[t] + v[t] == g[t];
sol = DSolveValue[{ode, v[0] == z}, v, t];
Plot[Evaluate[sol[t] /. { z -> {0, 1, 2, 3}, R -> 2, c -> 0.3}], {t, 0, 6},  PlotLegends -> {"V = 0", "V = 1", "V = 2", "V = 3"}]

This shows four different lines, but all the same color and with only one legend. I have also tried doing Expressions, AllExpressions, and All and none of these worked either. I'm extremely new to Mathematica so you might have to spell out what I'm doing wrong. Thanks!

$\endgroup$

closed as off-topic by Sektor, corey979, MarcoB, rcollyer, b3m2a1 Jan 19 '18 at 6:45

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Sektor, corey979, MarcoB, rcollyer, b3m2a1
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ Plot[Evaluate[ Table[sol[t] /. {z -> z0, R -> 2, c -> 0.3}, {z0, {0, 1, 2, 3}}]], {t, 0, 6}, PlotLegends -> {"V = 0", "V = 1", "V = 2", "V = 3"}] $\endgroup$ – corey979 Jan 10 '18 at 19:24
  • 1
    $\begingroup$ To add to corey's comment, z -> {0, 1, 2, 3} is substituting in the full list, and sol isn't being applied to them separately. So, that's why he suggests using Table. $\endgroup$ – rcollyer Jan 17 '18 at 18:18
1
$\begingroup$
g[t_] := Piecewise[{{2, t <= 3}, {0, t > 3}}]
ode = R*c*v'[t] + v[t] == g[t];
vF[z_] = DSolveValue[{ode, v[0] == z}, v, t] /. {R -> 2, c -> 0.3}

With[{zvals = Range[0, 3]},
  Plot[Evaluate @ Through[(vF /@ zvals)[t]], {t, 0, 6},
    PlotLegends -> (Row[{"V = ", #}] &) /@ zvals]]

plot

You could also write

Plot[Evaluate @ Through[(vF /@ #)[t]], {t, 0, 6},
  PlotLegends -> (Row[{"V = ", #}] &) /@ #] & @ Range[0, 3]

but that's getting a little too much like code golf and too obscure for me to be happy with it.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.