David
David

Reputation: 769

How can I colour specific data bars in R Histogram

If I have a histogram:

> hist(faithful$waiting,seq(min(faithful$waiting),max(faithful$waiting)))

and a list of "special" frequencies:

> c(51, 52, 57, 59, 64)

is it possible to colour the bars corresponding to these special frequencies a different colour from the rest of the histobram?

Upvotes: 4

Views: 684

Answers (2)

JasonAizkalns
JasonAizkalns

Reputation: 20463

Fun with ggplot2...

faithful$special <- faithful$waiting %in% c(51, 52, 57, 59, 64)

library(ggplot2)

ggplot(data = faithful, aes(x = waiting, fill = special)) +
  geom_histogram(binwidth = 1, colour = 'white')

enter image description here

Upvotes: 2

cdeterman
cdeterman

Reputation: 19960

You could simply create a vector of the colors and use the col option.

data(faithful)

# make sure frequencies in order and unique for the histogram call
special <- ifelse(sort(unique(faithful$waiting)) %in% c(51, 52, 57, 59, 64), "red", "white")

# same call with the 'col' option
hist(faithful$waiting,seq(min(faithful$waiting),max(faithful$waiting)), col=special)

enter image description here

Upvotes: 4

Related Questions