2015-07-04 4 views
1

При использовании geom_histogram в ggplot и position = "identity" можно выбрать порядок, по которому сначала идет цвет?оверлейная гистограмма по определенному порядку цвета заливки

a <- data.frame(rep(1:10, each = 4)) 
b <- data.frame(rep(1:3, each = 5)) 
c <- data.frame(rep(4:9, each = 3)) 
names(a) <- "num" 
names(b) <- "num" 
names(c) <- "num" 
a$color <- "red" 
b$color <- "white" 
c$color <- "blue" 

abc <- rbind(a,b,c) 

ggplot() + geom_histogram(data = abc, aes(x=num, fill = color), 
position = "identity") + scale_fill_identity() 

Можно ли построить белый, затем красный, а затем синий?

ответ

2

Два способа

## Make color a factor 
abc$color <- as.factor(abc$color) # "blue" "red" "white" 

## Using desc to reverse order in aes 
ggplot() + geom_histogram(data = abc, aes(x=num, fill = color, order=desc(color)), 
          position = "identity") + scale_fill_identity() 

## Manually reorder factors 
abc$color <- with(abc, factor(color, levels(abc$color)[3:1])) 
ggplot() + geom_histogram(data = abc, aes(x=num, fill = color), 
          position = "identity") + scale_fill_identity() 

enter image description here

Смежные вопросы