How to stop barchart from hiding labels for data value 0 in Mathematica?
Asked Answered
D

3

7

I use this to create a Bar Chart:

BarChart[
 Reverse@data,
 BarOrigin -> Left,
 ChartLabels -> 
  Placed[{Reverse@labels, Reverse@data}, {Before, After}],
 ChartElementFunction -> "FadingRectangle"
 ]

With data = {7, 10, 0, 6, 0, 3, 5} this gives

Mathematica graphics

The problem is that some of the data values are 0 and BarChart won't even add labels for them. Instead it leaves a open space. How can I get it to still add the labels even though the values are 0?

This is with Mathematica 8.

Dratted answered 12/1, 2012 at 19:21 Comment(2)
Possibly related: Not cropping BarChart when using Frame instead of AxesChevrette
It's a rough workaround, but if nothing better comes up, you can do BarChart[Reverse[data /. x_ /; x == 0 -> 10^-5], ... (i.e. replace zeros with small numbers just before plotting). I used the pattern x_ /; x == 0 to match both 0 and 0.0 ... I guess 0|0.0 would have been good as well.Chevrette
T
6

What about

data = {7, 10, 0, 6, 0, 3, 5}

labels = ("label " ~~ ToString[#]) & /@ data

BarChart[Reverse@data, BarOrigin -> Left,
ChartLabels -> Placed[{Reverse@labels, Reverse@data}, {Axis, After}],
ChartElementFunction -> "FadingRectangle"]

It seems that "Before" doesn't and "Axis" does work?

chart

Tartuffe answered 12/1, 2012 at 21:12 Comment(1)
This looks like the cleanest solution, even if you still loose the second labels.Dratted
K
3

The simplest approach is to use a hack like data /. {(0|0.0) -> 0.00001}.

I think this should work without the need for a hack, so you should also file a report with [email protected].

Kaki answered 12/1, 2012 at 19:46 Comment(2)
I realize I made a mistake when I edited a sample dataset and plot into the question: the dataset might be real numbers, so 0|0.0 -> 0.00001 or something similar would be better.Chevrette
@Chevrette Good point. I added your approach (after briefly considering PossibleZeroQ...)Kaki
P
2

Your code works as given in Mathematica 7 on Windows 7.

data = {7, 10, 0, 6, 0, 3, 5};

labels = Row[{"label",#}]& /@ data;

BarChart[
  Reverse@data,
  BarOrigin -> Left,
  ChartLabels ->
   Placed[{Reverse@labels, Reverse@data}, {Before, After}],
  ChartElementFunction -> "FadingRectangle"
]

Mathematica graphics

Phyl answered 12/1, 2012 at 22:19 Comment(1)
I suppose I should have specified I'm using Mathematica 8.Dratted

© 2022 - 2024 — McMap. All rights reserved.