0

Hello I want to segment a histogram into several parts with different colors. For example, the blue color in values ​​less than 0.3, red values ​​between 0.3 and 0.5, the green values ​​between 0.5 and 0.7 ... etc.

Any idea?

Muramasa
  • 163
  • 2
  • 13

4 Answers4

6

enter image description hereCheck col argument and histogram breaks property. See example below:

set.seed(0)
x = rnorm(100, mean=0.5, sd=0.5)
h = hist(x, breaks=10, plot=F)

colors = rep("blue", length(h$breaks))
colors[h$breaks >= 0.3] = "red"
colors[h$breaks >= 0.5] = "green"
colors[h$breaks >= 0.7] = "orange"
hist(x, breaks=10, col=colors)
Baumann
  • 1,119
  • 11
  • 20
2

How about ggplot2

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

enter image description here

Troy
  • 8,581
  • 29
  • 32
1

Color has to be set for each pillar. I this example there are 8 pillars => you need to post 8 colors to hist

  set.seed(123)
    a<-rnorm(20)
    hist(a)
    col<-c(rep("red",2),rep("blue",6))
    hist(a,col=col)

Baumann's answer is much nicer!

Rentrop
  • 20,979
  • 10
  • 72
  • 100
1

The previous answers are great if you want entire bars to be the same color. If you want the transitions to be at the exact values stated even if the breaks in the bars don't match, then here in another approach (using base graphics):

set.seed(0)
x = rnorm(100, mean=0.45, sd=0.25)

hist(x, col='blue')

tmp <- par('usr')
clip(0.3,0.5, tmp[3], tmp[4])
hist(x, col='red', add=TRUE)

clip(0.5, tmp[2], tmp[3], tmp[4])
hist(x, col='green', add=TRUE)
Greg Snow
  • 48,497
  • 6
  • 83
  • 110