2017-03-08 54 views
0

我正在尝试生成几个甘特图,每个甘特图都有不同数量的条目。我将该行的颜色映射到一个因素(来源)。在下面的例子中,“大”和“小”图表中的因子水平相同,但是当绘制时,归因于每个水平的颜色会发生变化(即“收音机”在第一个是绿色的,第二个是红色的)!ggplot2:因子水平与行颜色的一致映射

如何确保所有图都具有相同的颜色映射?

# Generate vectors: 
name <- paste("person", seq(10), sep = '_') 
start <- sample(seq(5), size = 10, replace = T) 
end <- sample(seq(6,10), size = 10, replace = T) 
source <- factor(c('radio','tv','radio','tv','radio','tv','book','wordofmouth','book','book')) 

# Generate data frames: 
big_chart <- data.frame(name = c(name,name), value = c(start,end), source) 
small_chart <- big_chart[c(1:2,11:12),] 

library(ggplot2) 
ggplot(big_chart, aes(value, name, colour = as.factor(source))) + 
    geom_line() 

ggplot(small_chart, aes(value, name, colour = as.factor(source))) + 
    geom_line() 

enter image description here

enter image description here

+1

'ggplot(small_chart,AES(值,名称,颜色=源)) + geom_line()+ scale_colour_discrete(drop = FALSE)' – beetroot

回答

0

甜菜已经提供了完全为我工作溶液:

ggplot(small_chart, aes(value, name, colour = source)) + geom_line() + scale_colour_discrete(drop = FALSE)