I have a function of two variables

f[x_,t_]:= ...

and I want to build a command that plots the list of functions {f[x,t_i]} given any list of parameter values {t_i}. For example, I'd like


to effectively execute the command


I'd also like to add a plot legend that labels each function as "t = (value)" where (value) is t_i. This seems simple enough but I'm not so familiar with manipulating lists in Mathematica. Any advice is appreciated.


1 Answer 1

f[x_, t_] := x + t
ts = Range[3]
exprs = f[x, #] & /@ ts
lbls = StringTemplate["t=``"] /@ ts
Plot[Evaluate@exprs, {x, 0, 10}, PlotLegends -> lbls]
  • $\begingroup$ Actually this is giving me some trouble when I try to use it on my real example. The problem (I think) is that my function f has NIntegrate commands, which it is trying to evaluate at the line exprs = f[x,#]&/@ts. It can't evaluate these without actual values for x, so it throws errors. $\endgroup$
    – WillG
    Commented Nov 7, 2019 at 19:11
  • $\begingroup$ Is there a way I can use something like f[x,#]/@ts without having MM actually try to evaluate f at this point? I just want it to automatically generate the list with other variables as placeholders so that it can be safely plugged into Plot. $\endgroup$
    – WillG
    Commented Nov 7, 2019 at 19:13
  • 4
    $\begingroup$ @WillG You might want to try f[x_?NumericQ, t_?NumericQ] := .... This should prevent MMA from evaluating f[x, t] until it has actual numbers that it can use. $\endgroup$
    – MassDefect
    Commented Nov 7, 2019 at 19:18
  • $\begingroup$ Thanks, that did the trick. $\endgroup$
    – WillG
    Commented Nov 7, 2019 at 20:50
  • $\begingroup$ For posterity, I also had to throw in an "Evaluate[ ]" around the first argument of Plot when I wrote out "exprs" explicitly in that slot. I.e., "Plot[f[x,#]&/@ts,...]" and "Plot[Evaluate@f[x,#]&/@ts,...]" did not work, but "Plot[Evaluate[f[x,#]&/@ts],...]" did work. $\endgroup$
    – WillG
    Commented Nov 7, 2019 at 20:53

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.