How to use multiple fields as label on a bar chart in Tableau
Recently, I created a visualization in tableau that uses a bar chart to represent multiple information across several fields. The bar chart was supposed to work in such a way that selecting a field changes information on the bar chart and updates the bar labels to show the correct data.
I had nine fields and I placed all the nine fields on the label marks card so that when a field is selected, the label for that field shows at the end of the bars.
Placing nine fields into the label marks card made the result messy and I couldn’t understand why. In the past, I have only had to place a maximum of two fields in the label marks card.
I searched the internet for about half an hour for a solution but to no avail. The only option I had left was to figure it out on my own. I tried several approaches during which I realized that the label marks card can only take a maximum of two fields, else the behavior becomes disproportionate as seen in the image above.
Placing a third field on the label marks card would disorder the labeling. So I thought of a way to merge the nine fields into one. I realized that I could achieve this by writing a conditional
IF statement in VizQL which uses the current value of the
[Measure Parameter] to determine which label is shown at the end of the bars. It also ensures that when the information displayed on the bar chart changes, the labels are updated accordingly and are aligned correctly.
The code used is shown below:
IF [Measure Parameter]='Drawn' THEN [Drawn]
ELSEIF [Measure Parameter]='Goal Difference' THEN [Goal Difference]
ELSEIF [Measure Parameter]='Goals Against' THEN [Goals Against]
ELSEIF [Measure Parameter]='Lost' THEN [Lost]
ELSEIF [Measure Parameter]='Goals For' THEN [Goals For]
ELSEIF [Measure Parameter]='Played' THEN [Played]
ELSEIF [Measure Parameter]='Points' THEN [Points]
ELSEIF [Measure Parameter]='Position' THEN [Position]
ELSEIF [Measure Parameter]='Won' THEN [Won]
In the code snippet shown above, the nine fields being toggled are: Drawn, Goal Difference, Goals Against, Lost, Goals, Played, Points, Position and Won.
Using the code above gave the desired result as seen below;
I hope this helps someone out there.
Thank you for reading.