15
$\begingroup$

Suppose I have a function that I want to plot for several values of a parameter all in the same window. For instance the function $f$ defined as

f[a_,b_,c_,d_]:= a+Sin[b]*Exp[c]-d^4

If I now want to plot f[a,1,2,3] with respect to a from 0 to 1 I simply write

Plot[f[a,1,2,3],{a,0,1}]

But suppose I want to instead plot f[a,b,2,3] same as before for a from 0 to 1 but now the parameter b takes on several values, say b = 0,1,2,3,4 and so on. How can I do this all in the same plot (preferably with different colors on each curve corr. to the various b-values)?

$\endgroup$
3
  • $\begingroup$ You've seen Table[]? $\endgroup$ Oct 12, 2015 at 14:23
  • $\begingroup$ I'll look it up. $\endgroup$ Oct 12, 2015 at 14:24
  • $\begingroup$ @J.M.isback. OK I see what `Table[]' can do, but how can one implement it to write a smooth short code? Any tips? $\endgroup$ Oct 12, 2015 at 14:26

1 Answer 1

16
$\begingroup$

You can use Table for this:

Plot[Evaluate@Table[f[a, b, 2, 3], {b, 0, 5, 1}], {a, 0, 1}]

And you can also put there multiple parameters, so Table will use all of them.

enter image description here


You can use PlotLegend to specify the legend:

Plot[Evaluate@Table[f[a, b, 2, 3], {b, 0, 5, 1}], {a, 0, 1}, 
 PlotLegends -> LineLegend[Table[b, {b, 0, 5, 1}], LegendLabel -> x]]

enter image description here

$\endgroup$
8
  • $\begingroup$ ooo sexy, I'll try it out and report back here. $\endgroup$ Oct 12, 2015 at 14:27
  • $\begingroup$ Is there a simple way to add names to all the lines, e.g. some type of legend that explains? I mean I know I can write PlotLegends -> {"1","2",...} and so on, but a more automatic code would be nice. Sorry to bother you so much. $\endgroup$ Oct 12, 2015 at 14:32
  • $\begingroup$ @ShutupandCalculate look up PlotLegends. $\endgroup$
    – rcollyer
    Oct 12, 2015 at 14:34
  • $\begingroup$ Also, there's an undocumented option: Evaluated that when set to True operates just like using Evaluate. $\endgroup$
    – rcollyer
    Oct 12, 2015 at 14:35
  • 1
    $\begingroup$ Try adding PlotTheme -> "Detailed" as an option for Plot for good looking plots with automatic labels. $\endgroup$
    – rhermans
    Oct 12, 2015 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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