David Z
David Z

Reputation: 7061

barplot color by values in R

suppose I have a barplot in R:

set.seed(123)
x<-rnorm(10)
barplot(x)

what I wanted is to fill the bar with blue if x<=0 and red otherwise. I have been trying barplot and ggplot2(which I would prefer if possible), but haven't found a better solution yet. If the filled colors can change gradually from blue (min) to red (max).

Upvotes: 0

Views: 538

Answers (1)

Se&#241;or O
Se&#241;or O

Reputation: 17432

You can do this with ggplot:

ggplot(data.frame(Index = 1:length(x), value = x), aes(Index, value, fill = value >= 0)) + geom_bar(stat = "identity")

enter image description here

Upvotes: 1

Related Questions