3
$\begingroup$

a quick question:

I am trying to label a BarChart that consists of two lists (groups). The label should keep going on with the Label list (so ddd, eee, fff) and not repeat itself (and start from aaa, bbb...) after the first group ends (see picture underneath)

A simplified code:

  BarChart[{{1, 2, 3}, {4, 5, 6}}, 
 ChartLabels -> {aaa, bbb, ccc, ddd, eee, fff}, 
 ChartStyle -> {{Red, Green}, None}]

enter image description here

With the dataset:

enter image description here

$\endgroup$
1
  • $\begingroup$ try: ChartLabels -> {{aaa, bbb, ccc}, {ddd, eee, fff}} $\endgroup$
    – demm
    Jan 6 '20 at 14:23
5
$\begingroup$
data = {{1, 2, 3}, {4, 5, 6}};
labels = {aaa, bbb, ccc, ddd, eee, fff};
labeleddata = TakeList[MapIndexed[Labeled[#, labels[[#2[[1]]]]] &, 
  Flatten @ data], Length /@ data]

BarChart[labeleddata, ChartStyle -> {{Red, Green}, None}]

enter image description here

You can also define labeleddata as

labeleddata = MapThread[Labeled] /@ Transpose[{data, TakeList[labels, Length /@ data]}]

Update: An alternative approach using the option LabelingFunction:

ClearAll[labelingF]
labelingF[data_, labels_] := 
 Association[
  Flatten@MapIndexed[#2 -> # &, TakeList[labels, Length /@ data], {2}]]

Examples:

data = {{1, 2, 3}, {4, 5, 6, 7, 8}};
labels = {aaa, bbb, ccc, ddd, eee, fff, ggg, hhh};

BarChart[data, ChartStyle -> {{Red, Green}, None}, 
 LabelingFunction -> (Placed[Rotate[#, 60 Degree] &@labelingF[data, labels]@#2, Below] &)]

enter image description here

Use data = {{1, 2, 3}, {4, 5, 6}, {7, 8}} and ChartStyle -> {{Red, Green, Orange}, None} to get

enter image description here

$\endgroup$
3
  • $\begingroup$ Thanks! Unfortunately it only takes the first two values of the list (I added a screenshot above), do you know why this is? $\endgroup$
    – Faye Drew
    Jan 6 '20 at 15:03
  • $\begingroup$ @FayeDrew, please see the updated version. $\endgroup$
    – kglr
    Jan 6 '20 at 15:28
  • $\begingroup$ Thank you!! This worked! $\endgroup$
    – Faye Drew
    Jan 6 '20 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.