Home > Enterprise >  Plot with conditional colors based on values in hist
Plot with conditional colors based on values in hist

Time:07-15

Is it possible to have the bars painted in only one color whose condition is X < 980? in the histogram below.

R code:

Sample <- rnorm(2500,1000,20) # 2500 norm values
plot(Sample, col = ifelse(Sample < 980,'red','green')) # Paint in 'red' when X<980

enter image description here

CodePudding user response:

You could determine the colors according to the mid-point of each bin.

Sample <- rnorm(2500, 1000, 20)
h <- hist(Sample, plot = FALSE)
hist(Sample, col = ifelse(h$mids < 980, 'red', 'green'))

enter image description here

CodePudding user response:

Update: changed length(my_breaks) to length(my_breaks)-1 thanks to @Darren Tsai.

This one is similar to @Adam Querk solution: First we define our breaks, then the custum colors and finally plot the histogram.

my_breaks <- hist(Sample)$breaks

my_colors <- rep('green', length(my_breaks)-1)
my_colors[my_breaks < 980] <- 'red'
my_colors[my_breaks > 980] <- 'green'

hist(Sample, col=my_colors)

enter image description here

CodePudding user response:

You can manually set breaks and assign the colours.

set.seed(4)
Sample <- rnorm(2500,1000,20)
hist(Sample, breaks = seq(920, 1080, 10), col = c(rep("red", 6), rep("green", 10))) 

enter image description here

CodePudding user response:

Using ggplot2 you could do this by setting the 'fill aesthetic'

library(ggplot2)
set.seed(1) # setting seed so the random numbers are consistent (for example)

# create a data frame with 'Sample' as a column
df <- data.frame(Sample = rnorm(2500,1000,20))  # 2500 norm values

# create plot setting the 'fill' colour based on your logical test Sample<980
ggplot(data = df,
       mapping = aes(x = Sample,
                     fill = Sample<980))  
  geom_histogram()  
  scale_fill_manual(values = c("green","red")) # set specific colours

This will give the following output:

histogram of a normal distribution with values < 980 highlighted red 1

If you want to pick the bins so that one has a boundary at exactly 980, and also if you want to add the black outlines, you could achieve this as follows:

ggplot(data = df,
       mapping = aes(x = Sample,
                     fill = Sample<980))  
  geom_histogram(binwidth = 10,
                 center = 980 - 10/2, # set bin center at half a bin width 
                                      # from the desired cutoff 
                 colour = "black")    # adding colour inserts the black border
  scale_fill_manual(values = c("green","red"))

histogram of normal distribution with boundary at 980 and black borders 2

  • Related