1
$\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$
3
  • 2
    $\begingroup$ Take a look at what ChartLabels -> First[#] & /@ example is doing. You need a bracket around the second part: ChartLabels -> (First[#] & /@ example) $\endgroup$ Commented Jun 7, 2013 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$ Commented Jun 7, 2013 at 9:10
  • 1
    $\begingroup$ Much better: BarChart[Last /@ example, ChartLabels -> First /@ example] or BarChart[example[[All, 2]], ChartLabels -> example[[All, 1]]]. $\endgroup$ Commented Jun 7, 2013 at 9:10

1 Answer 1

6
$\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$
1
  • 3
    $\begingroup$ If you take a look at FullForm[HoldForm[ChartLabels -> First[#] & /@ example]], you can instantly see what exactly is going wrong. $\endgroup$ Commented Jun 7, 2013 at 9:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.