2013-10-18 91 views
2

我想添加颜色到我的ggplot,但我似乎无法得到它的工作。我有一个函数PlotAllLayers,它自动将我的data.frame中的所有内容添加到图中。现在我想添加'Dark2'调色板,但它似乎不起作用。ggplot:阴谋中没有颜色

library(ggplot2) 
x <- c(0:100) 
df <- sapply(seq(5,100,by=10), function(n) dbinom(x,n,.6)) 
df <- data.frame(x,df) 

plotAllLayers<-function(df){ 
    p<-ggplot(data=df,aes(df[,1])) 
    for(i in names(df)[-1]){ 
    p<-p+geom_line(aes_string(y=i)) 
    } 
    return(p) 
} 

testplot <- plotAllLayers(df) 
testplot <- testplot + scale_color_brewer(palette="Dark2") 
print(testplot) 
+3

请不要在脚本的顶部包含'rm(list = ls(all = TRUE))'''。有时,我们会将重要的数据加载到我们的会话中,并且很容易无故地复制您的脚本并清除所有数据。 – nograpes

回答

5

您在一个函数中迭代添加图层的技巧会强制您迭代地指定颜色名称。这不是使用ggplot的规范方法。相反,melt你的数据第一,一切都变得容易:

library(reshape2) 
library(ggplot2) 
# Melt your data: 
melted.df<-melt(df,id.vars='x') 
# x variable value 
# 1 0  X1 0.01024 
# 2 1  X1 0.07680 
# 3 2  X1 0.23040 

# Plot. 
ggplot(melted.df,aes(x=x,y=value,colour=variable)) + 
    geom_line() + 
    scale_color_brewer(palette="Dark2") 
# Warning that this palette doesn't support 10 colours. 
+0

我爱你。这完美解决。 – Bijan

+1

请将数据添加到您的问题中!我只是想删除第一行。另外,如果您喜欢答案,请点击答案左侧的复选标记。 – nograpes