Alanis Alanis - 1 year ago 34
R Question

Colouring a histogram beyond a certain value

Firstly I know this question has come up before, namely: Change histogram bar colours greater than a certain value
but despite that thread, I'm running into a confusing issue.

So, I have some data, and within that data I know that the variable houses$PPSQM has 4 values greater than 3000. So what I was trying to do was plot a histogram of the data with all the bars below 3000 being red and the ones above 3000 being grey. I know from viewing the histogram that there are 2 bars that are above 3000(for the sake of clarity, there's 2 values at 4000 and 2 at 5000) here's the code I was using:

clr <- ifelse(houses$PPSQM>3000, "grey", "red")

hist(houses$PPSQM,ylim = c(0, 50) ,xlab="Cost per Sq. Meter",ylab='Frequency',col = clr)

But the problem I'm having is: If I say houses$PPSQM>3000, in the if-else statement, then it's colouring all the bars red... and if I say houses$PPSQM<3000, then it's colouring all the bars grey!?

Any suggestions as to how I'd fix this?

Answer Source

I think you need to colour by breaks in the histogram, not by values in the data. Try this:

h   <- hist(houses$PPSQM)
clr <- ifelse(h$breaks > 3000, "red", "grey")
hist(houses$PPSQM, ylim = c(0, 50), xlab = "Cost per Sq.Meter", 
     ylab = 'Frequency', col = clr)

You might need to play with the breaks parameter (see ?hist) to get it looking how you want. You might also want to use >= 3000.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download