2015-07-04 60 views
1

當在ggplot中使用geom_histogram和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