4
$\begingroup$

My goal is to draw dots whose positions can be adjusted. I could draw a fixed number of dots, say 2 and 5, like the code below. If the user sets the number of dots, how do I create dots and sliders according to that number?

Manipulate[
 NumberLinePlot[{a, b}, PlotStyle -> {Black, Red}, 
  PlotRange -> {0, 4}], {{a, 1.5}, 0, 4}, {{b, 1}, 0, 4}]

enter image description here

Manipulate[
 NumberLinePlot[{a, b, c, d, e}, PlotStyle -> {Black, Red}, 
  PlotRange -> {0, 4}], {{a, 1.5}, 0, 4}, {{b, 1}, 0, 4}, {{c, 1.2}, 
  0, 4}, {{d, 1.3}, 0, 4}, {{e, 1.4}, 0, 4}]

enter image description here

$\endgroup$

1 Answer 1

9
$\begingroup$

The easiest way is to use a nested Manipulate:

DynamicModule[{numbers},
 Manipulate[
  Manipulate[
   NumberLinePlot[Lookup[numbers, Range[n], 0],
    PlotStyle -> {Black, Red}, PlotRange -> {0, 4}],
   Column[
    Slider[Dynamic[numbers[#]], {0, 5}] & /@ Range[n]
    ]
   ],
  {n, 1, 10, 1},
  Initialization :> (numbers = <||>)
  ]
 ]
$\endgroup$
2
  • 1
    $\begingroup$ Clever. Where did you find that the controls are placed in an association by specifying: Initialization :> (numbers = <||> $\endgroup$ Commented Sep 13, 2023 at 15:57
  • 1
    $\begingroup$ @DanielHuber I don't remember, but when you have something like Slider[Dynamic[expr], ...], you get a control that continuously evaluates expr = controlSetting. So if the expression points to the part of an association or a list, it just uses Part assignment like it normally does. $\endgroup$ Commented Sep 13, 2023 at 16:22

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.