4
$\begingroup$

I would like to create a list of parameters, then create a Manipulate with these parameters. Similar to this piece of code:

(* code that generates manipulate parameters *)
bars = Array[b, 5];
(* code that generates manipulate *)
Manipulate[
 BarChart[bars, PlotRange -> {0, 2}],
 Evaluate[Sequence @@ ({#, 0, 2} & /@ bars)]]

Manipulate displays 5 controls for b[1]..b[5], but the BarChart always stays empty - I think bars isn't evaluated, but I couldn't figure out how to make Manipulate evaluate it.

This works, but isn't dynamic any more:

bars = Array[b, 5];
Manipulate[
 BarChart[{b[1], b[2], b[3], b[4], b[5]}, PlotRange -> {0, 2}],
 Evaluate[Sequence @@ ({#, 0, 2} & /@ bars)]]

(i.e. if the code above decides to create 4 or 6 entries in bars it won't work any more)

$\endgroup$
1
  • 1
    $\begingroup$ With[{bars = bars}, Manipulate[BarChart[bars, PlotRange -> {0, 2}], Evaluate[Sequence @@ ({#, 0, 2} & /@ bars)]] ]? $\endgroup$
    – Michael E2
    Commented Sep 5, 2016 at 16:53

1 Answer 1

4
$\begingroup$

You can inject the evaluated bars with With:

With[{bars = bars},
 Manipulate[BarChart[bars, PlotRange -> {0, 2}], 
  Evaluate[Sequence @@ ({#, 0, 2} & /@ bars)]]
 ]

Mathematica graphics

Or with a function:

manFN = Function[bars, 
   Manipulate[BarChart[bars, PlotRange -> {0, 2}], 
    Evaluate[Sequence @@ ({#, 0, 2} & /@ bars)]]
   ];

manFN[Rest@bars] (* Rest@.. to show dependence on argument *)

Mathematica graphics

$\endgroup$
3
  • $\begingroup$ Perfect, thanks! $\endgroup$ Commented Sep 5, 2016 at 17:58
  • $\begingroup$ @nikie You're welcome! $\endgroup$
    – Michael E2
    Commented Sep 5, 2016 at 18:13
  • $\begingroup$ @MichaelE2 For readability I prefer to not use Evaluate. One way is With[{bars = bars, controls = Sequence @@ Map[{#, 0, 2} &]@bars}, Manipulate[BarChart[bars, PlotRange -> {0, 2}], controls]] $\endgroup$ Commented Sep 5, 2016 at 18:43

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.