6
$\begingroup$

In the Add Error Bars to Charts and Plots How To in the Mathematica documentation a function ErrorBar is given:

errorBar[type_: "Rectangle"][{{x0_, x1_}, {y0_, y1_}}, value_, meta_] := 
   Block[{error}, 
      error = Flatten[meta];
      error = If[error === {}, 0, Last[error]]; 
      {ChartElementData[type][{{x0, x1}, {y0, y1}}, value, meta], 
         {Black, Line[{
             {{(x0 + x1)/2, y1 - error}, {(x0 + x1)/2, y1 + error}}, 
             {{1/4 (3 x0 + x1), y1 + error}, {1/4 (x0 + 3 x1), y1 + error}}, 
             {{1/4 (3 x0 + x1), y1 - error}, {1/4 (x0 + 3 x1), y1 - error}}
            }]
       }}
      ]

that adds error bars to BarChart. Here is an example using some random data with random errors:

chartData = MapThread[{#1 -> #2} &, {RandomReal[1, 10], RandomReal[0.1, 10]}]

and some random labels:

labels = ToString /@ RandomReal[100000, 10]

Now plotting it, as per the tutorial:

BarChart[chartData, ChartElementFunction -> errorBar["Rectangle"], 
ChartLabels -> Placed[labels, Axis, Rotate[#, Pi/2] &]]

The labels are:

{"99539.6", "17862.9", "14683.4", "32667.2", "42690.", 
 "70230.8", "59050.4", "59204.7", "9138.2", "19080.3"}

However, in the plot:

Mathematica graphics

The first label is repeated incorrectly for all the bars, what's going on here? Without error bars the labels on the plot are correct:

Mathematica graphics

BarChart[RandomReal[1, 10], ChartLabels -> Placed[labels, Axis, Rotate[#, Pi/2] &]]
$\endgroup$

1 Answer 1

7
$\begingroup$

In the original code, chartData is of the form {{value1 -> error1}, {value2 -> error2}, ... }, but it should be of the form {value1 -> error1, value2 -> error2, ... }. To get the right labels you could do something like (note the missing brackets in chartData)

chartData = 
 MapThread[#1 -> #2 &, {RandomReal[1, 10], RandomReal[0.1, 10]}];

BarChart[chartData, 
 ChartElementFunction -> errorBar["Rectangle"], 
 ChartLabels -> Placed[labels, Axis, Rotate[#, Pi/2] &]]

Mathematica graphics

$\endgroup$
2
  • 2
    $\begingroup$ Why use #1 -> #2 & and not simply Rule? $\endgroup$
    – Mr.Wizard
    Mar 7, 2012 at 0:39
  • $\begingroup$ @Mr.Wizard I would suspect #1 -> #2& is less opaque than Rule as I don't know how many users know that they're equivalent. $\endgroup$
    – rcollyer
    Mar 8, 2012 at 18:20

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.