4
$\begingroup$

I'm trying to get a BarChart to colour negative valued bars red and positive valued bars green but I'm having a time trying to do it. My latest attempt is:

data = {0.34`, 0.04`, 1.07`, -0.54`, -2.4`, 0.44`};
t = Piecewise[{{# >= 0, Green}}, Red] &;
BarChart[data, ChartLayout -> "Stepped", BarSpacing -> None,
 ColorFunction -> t, 
 ColorFunctionScaling -> False]

However this still colours the bars in the default colour. May someone tell me what I am doing wrong. I thought this would be pretty simple. I'm not getting an error. It just is ignoring the ColorFunction. I'm on 10.0.1

Thanks,

Edmund

$\endgroup$

1 Answer 1

5
$\begingroup$

You have inverted Piecewise arguments. Here is the right form:

data = {0.34, 0.04, 1.07, -0.54, -2.4, 0.44};
color=Piecewise[{{Green,# >= 0}}, Red] &;
BarChart[data
        ,ChartLayout -> "Stepped"
        ,BarSpacing -> None
        ,ColorFunction -> color
        ,ColorFunctionScaling -> False
    ]

Now it works:

enter image description here

I personaly prefer Which. Here is an example for accumulated color change using it:

color=Which[#<= 0,Red,True,Green]&;
BarChart[data
        ,ChartLayout -> "Stepped"
        ,BarSpacing -> None
        ,ChartStyle->color/@Accumulate@data
    ]

enter image description here

$\endgroup$
10
  • $\begingroup$ Why is the last bar green ? $\endgroup$
    – eldo
    Commented Oct 8, 2014 at 1:23
  • $\begingroup$ @Murta Thanks, that works great. But do you know why Piecewise isn't working? Shouldn't it work the same as Which? Also, I prefer Piecewise as it is not a programming construct as Which is. $\endgroup$
    – Edmund
    Commented Oct 8, 2014 at 1:30
  • $\begingroup$ @Murta Why is the fourth bar red and the last one green ? $\endgroup$
    – eldo
    Commented Oct 8, 2014 at 1:36
  • $\begingroup$ @eldo, it's a positive variation. So, it's green... $\endgroup$
    – Murta
    Commented Oct 8, 2014 at 1:37
  • $\begingroup$ Why downvote? Someone knows? $\endgroup$
    – Murta
    Commented Oct 8, 2014 at 1:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.