2
$\begingroup$

Assume, I have a Dataset like this

ds = Dataset[<|
   "Alice" -> <|"food" -> {"apple", "orange"}, 
     "drink" -> {"water", "tea"}|>,
   "Bob" -> <|"food" -> {"apple", "banana"}, 
     "drink" -> {"tea", "coffee"}|> ,
   "Eve" -> <|"drink" -> {"tea"}|>|>]

enter image description here

This data set consists of three individuals and each has observations for food and drink they consume.

I now want to, for example, plot the percentage of tea drinkers (100%), or the percentage (or number) of banana eaters (33%, 1 out of 3). Ideally this would be a `BarChart like this

enter image description here

where the first three a, b, c's would be apples, bananas, or oranges. The second group of a, b, c would be food items.

Please note that there can be missings (e.g. Eve doesn't have food items but she counts towards the three persons)

I tried something like

ds[BarChart, {All, All, "food"}]

but it doesn't work.

$\endgroup$
2
  • $\begingroup$ ds[BarChart[#, ChartLabels -> Automatic] &@*Map[Total]@*Transpose@* DeleteMissing@*Map[Counts], "food"] and ds[BarChart[#, ChartLabels -> Automatic] &@*Map[Total]@*Transpose@* DeleteMissing@*Map[Counts], "drink"]? $\endgroup$
    – kglr
    Nov 10, 2021 at 11:22
  • $\begingroup$ @kglr thanks, that's pretty close to what I want. How can I get percentages instead of counts? $\endgroup$
    – spore234
    Nov 10, 2021 at 12:04

1 Answer 1

4
$\begingroup$
ds2 = ds[Map[Merge[100 Total[#]/Length[ds] &] @* Values @* DeleteMissing] @*
   Transpose @* Map[Map[Counts]], {"food", "drink"}]

enter image description here

BarChart[Map[KeyValueMap[Labeled[#2, #] &]] @ #, 
   ChartLabels -> {Callout[Automatic], Automatic}] & @ ds2

enter image description here

Alternatively,

operator = BarChart[#, ChartLabels -> {Callout[Automatic], Automatic}] & @*
   Map[KeyValueMap[Labeled[#2, #] &] @*
       Merge[100 Total[#]/Length[ds] &] @*
       Values @* 
       DeleteMissing] @*
   Transpose @* 
   Map[Map[Counts]];

ds[operator, {"food", "drink"}]

enter image description here

op = Map[BarChart[#,  ChartLabels -> Automatic] & @* 
         Merge[100 Total[#] / Length[ds] &] @* 
         Values @*
         DeleteMissing] @* 
         Transpose @* 
         Map[Map[Counts]];

ds3 = ds[op]

enter image description here

ds3["food"]

enter image description here

ds3[Row[{Show[#"food", PlotLabel -> "food", ImageSize -> 300], 
    Show[#"drink", PlotLabel -> "drink", ImageSize -> 300]}] &]

enter image description here

$\endgroup$

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.