0

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?

Alanis
  • 27
  • 2
  • 4
  • Hi Alanis, if you can make the example reproducible it would be much easier to help you. – Daniel Anderson May 22 '17 at 22:00
  • It's difficult to answer without seeing your data, but I suspect the issue is that you have more colours in `clr` than there are bars in your histogram. Remember that a histogram is not a bar plot: the values are placed into bins, not counted separately. Try `h <- hist(houses$PPSQM)` then see if `length(clr)` is more than `length(h$counts)`. – neilfws May 22 '17 at 22:03
  • You were right, `lenght(clr)` equals 12535... and `length(h$counts)` equals 11. It's been one of those days... have it fixed now... thanks for your help – Alanis May 22 '17 at 22:15

1 Answers1

1

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.

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • Thanks, your comment above sent me on the right track to fixing it... which was by using the `breaks` parameter. Thanks for your help – Alanis May 22 '17 at 22:21