2
$\begingroup$

I would like to allow a user to manipulate the segments of a pie-chart, which is to be generated from a list of a specific format.

The code looks something like the following:

pieChartList = {
    {category1, 1},
    {category2, 2}
};

generatePieChart[dataList_List, plotLabel_String] :=
    Manipulate[
        PieChart[
            {category1, category2},
            PlotLabel -> plotLabel
        ],
        {{category1, 1}, 0, 10}, {{category2, 2}, 0, 10}
    ];

generatePieChart[pieChartList, "Test pie chart"]

As you can see, the lists are being written "manually," even though pieChartList contains all the information to generate the necessary structures. Is there an elegant way to generate the manipulation list automatically? In other words, if I were to add {category3, 3} to pieChartList, the function generatePieChart should pick up the new value automatically.

Thanks in advance for your help.

$\endgroup$

2 Answers 2

3
$\begingroup$

You can inject variables with ## and & @@:

generatePieChart[dataList_List, plotLabel_String] := 
  Manipulate[PieChart[dataList[[All, 1]], PlotLabel -> plotLabel], ##] & @@ 
   Thread@{dataList, 0, 10};

generatePieChart[{{category1, 1}, {category2, 2}, {category3, 3}}, "Test pie chart"]

enter image description here

$\endgroup$
2
$\begingroup$

First of all don't use _ in variable names as Mathematica will think it is a pattern.

Manipulate has the attribute HoldAll but Evaluate can be used to get around that, allowing us to create a correct variable specification out of the data list:

generatePieChart[dataList : { {_Symbol, _?NumericQ} ..}, opts___] :=
 Manipulate[
  PieChart[dataList[[All, 1]], opts],
  Evaluate[Sequence @@ Map[{#, 0, 10} &, dataList]]
 ]

generatePieChart[{{c1, 1}, {c2, 2}, {c3, 1/2}}, PlotLabel -> "Test πchart"]

pie

Sequence @@ Map[{#, 0, 10} &, dataList] creates the necessary specification for Manipulate in this case {{c1, 1}, 0, 10}, {{c2, 2}, 0, 10}, {{c3, 1/2}, 0, 10}

$\endgroup$

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.