0
library(ggplot2)

df <- data.frame(x = runif(100))
ggplot(df, aes(x)) + geom_histogram(binwidth = 0.1)

enter image description here

What if I wanted to color the bin that contains a specific value to "red" while the rest becomes "blue"? Like say the value 0.5 (which will be in the [0.5, 0.6) bin)?

Henrik
  • 65,555
  • 14
  • 143
  • 159
zero
  • 1,605
  • 3
  • 15
  • 24
  • I think you'll have to bin the data beforehand and then plot it in ggplot with a fill linked to the variable defining whether it will be blue or red. – Haboryme Jan 19 '17 at 20:25
  • I tried doing that. I created a new column of logical if it's inside the "bin" and then tried using that for the fill. It didn't work. It may be because: 1. I got the binning wrong (I just assumed it was closed to the left). or 2. I was doing something wrong. – zero Jan 19 '17 at 20:40
  • This previous post may help: http://stackoverflow.com/questions/28323642/r-ggplot2-histogram-conditional-fill-color – Ryan Morton Jan 19 '17 at 20:45
  • @RyanMorton I've already checked that and that's not the type of implementation I want. That added a new column that's a factor of whatever he was trying to subset. I just want the specific bin a specific value is binned into to be colored a certain way – zero Jan 20 '17 at 15:04

2 Answers2

0

I got the right effect with this

df <- data.frame(x = runif(100))
df$y <- ifelse(df$x > 0.46 & df$x < 0.65, df$x, NA)

ggplot(df, aes(x)) + 
     geom_histogram(binwidth = 0.1, fill = 4) +
     geom_histogram(aes(y), binwidth = 0.1, fill = 2, data = df)
  • I've also tried that but I keep getting a partial color for a bin -- like half a bin is red while the other is blue – zero Jan 20 '17 at 15:11
0

Ok I think I figured it out. All this time, I got the binning wrong. Apparently, it's centered around the value (not as it's starting point).

So the 0.5 bin will contain values between (0.45, 0.55) if the binwidth is 0.1. I thought it was 0.5 to 0.6, that's why I keep getting half values. Thanks for the help!

In the example given by @user127649, if you change it to:

df <- data.frame(x = runif(100))
df$y <- ifelse(df$x > 0.45 & df$x < 0.55, df$x, NA) <-- adjust the binwidth here. This is where I got the idea that it's centered around the breaks. 

ggplot(df, aes(x)) + 
     geom_histogram(binwidth = 0.1, fill = 4) +
     geom_histogram(aes(y), binwidth = 0.1, fill = 2, data = df)
zero
  • 1,605
  • 3
  • 15
  • 24