0
$\begingroup$

I have some data which I want to plot in a simple bar chart:

example = {{"Knowledge", 2}, {"Comprehension", 4}, {"Application", 0}, {"Analysis", 1}, {"Synthesis", 0}, {"Evaluation", 2}}

The first element of each pair should be the bar label, and the second should be the height of the bar. I can get the desired result using:

BarChart[Last[#] & /@ example, ChartLabels -> {"Knowledge","Comprehension","Application","Analysis","Synthesis","Evaluation"}]

enter image description here

But my real question is this:

Though

First[#] &/@ example

Returns

{"Knowledge", "Comprehension", "Application", "Analysis", "Synthesis", "Evaluation"}

When I try:

BarChart[Last[#]&/@example, ChartLabels->First[#]&/@example]

I get a graph without labels:

enter image description here

This seems like strange behaviour, can anyone shed some light, or suggest a fix?

$\endgroup$
  • 2
    $\begingroup$ Take a look at what ChartLabels -> First[#] & /@ example is doing. You need a bracket around the second part: ChartLabels -> (First[#] & /@ example) $\endgroup$ – Jonathan Shock Jun 7 '13 at 9:08
  • $\begingroup$ Well, that was easy! Sorry for the wasted time. If you add that as an answer I'll accept it. $\endgroup$ – nickjamesuk Jun 7 '13 at 9:10
  • 1
    $\begingroup$ Much better: BarChart[Last /@ example, ChartLabels -> First /@ example] or BarChart[example[[All, 2]], ChartLabels -> example[[All, 1]]]. $\endgroup$ – J. M. will be back soon Jun 7 '13 at 9:10
  • $\begingroup$ That is better, thanks for the input. $\endgroup$ – nickjamesuk Jun 7 '13 at 9:14
4
$\begingroup$

You have to be careful with passing in arguments to a function when you have a replacement. The problem is currently that:

ChartLabels -> First[#] & /@ example

is passing the elements of example into all of ChartLabels -> First[#] one by one. You need instead to be passing it only into the second argument and so all that is needed to solve the problem is a set of brackets:

ChartLabels -> (First[#] & /@ example)
$\endgroup$
  • 2
    $\begingroup$ If you take a look at FullForm[HoldForm[ChartLabels -> First[#] & /@ example]], you can instantly see what exactly is going wrong. $\endgroup$ – J. M. will be back soon Jun 7 '13 at 9:26

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.