4
$\begingroup$

How can I apply a LabelingFunction with an if else condition? Suppose you have the following plot:

BarChart[{4, 3, 2, 1}, BarOrigin -> Left, LabelingFunction ->(Placed[#,Left] &)]

enter image description here

I want to plot it with the first two labels justified as they currently are (left), and the third and fourth label in bold and justified to the right.

$\endgroup$
3
$\begingroup$

It is important to always read the "Details" section of a symbol's documentation: LabelingFunction. There is it explained how to compute the label based on the element's index rather than its value:

LabelingFunction->f specifies that each chart element should have a label given by f[value,index,lbls], where value is the data value associated with the element, index is its position in the nested list of datasets, and lbls is the list of relevant labels.

To understand better what is being passed to the function, simply display all values in the label:

BarChart[data, BarOrigin -> Left, 
 LabelingFunction -> (Placed[{##}, Left] &)]

enter image description here

Now that we understand the structure of indices better, we can write our labelling function appropriately:

BarChart[data, BarOrigin -> Left, 
 LabelingFunction -> 
  Function[{value, index, label}, 
   If[Last[index] > 2, 
    Placed[Style[value, Bold], Right], 
    Placed[value, Left]]]]

enter image description here

| improve this answer | |
$\endgroup$
1
$\begingroup$
BarChart[{4, 3, 2, 1}, BarOrigin -> Left,LabelingFunction -> (Placed[#, If[# <= 2, Left, Right]] &)]

will answer your question! Bold might be realized similar...

| improve this answer | |
$\endgroup$

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.