2017-04-24 71 views
0

我有一个N列的数据框(事先不知道)包含X_1,X_2,... X_N每天的值。我需要能够绘制X_1,X_2,... X_N将多个数据添加到ggplot?

colors_list <- palette(rainbow(length(N))) 
p <- ggplot(Store_Data.df, aes(x = Day)) + ylab(label="Value") + xlab("Time") + 
geom_line(aes(y = Data.df$V1, colour=colors_list[1])) + 
geom_line(aes(y = Data.df$V2 colour=colors_list[2])) + 
. 
. 
. 
geom_line(aes(y = Data.df$V2 colour=colors_list[N])) 

怎么可以这样对abitary N,即实现,而不必硬线的代码。我试图遍历所有的列中的数据,即

colors_list <- palette(rainbow(length(N))) 
p <- ggplot(Store_Data.df, aes(x = Day)) + ylab(label="Value") + xlab("Time") 
for (i in 1:N){ 
    p <- p + geom_line(aes(y = Data.df$[,i], colour=colors_list[i])) 
} 

但情节仅示出了最后一组值,即Y = Data.df $ [,N]。如何才能做到这一点?

+0

请参阅[这里](http://stackoverflow.com/questions/5963269)关于做一个可重复的例子作为指导,以帮助我们回答您的问题。 –

回答

0

ggplot只允许将一列指定为y变量,因为它基于长格式而不是宽格式。

要得到你想要的最简单的方法,就是将数据重塑为长格式,然后按颜色分组。

这是一个使用R中的swiss数据集和重塑包中的熔化函数的快速示例。

require(reshape2) 
swiss_soldiers<-swiss #data in wide format 
swiss_soldiers<- melt(swiss_soldiers, "Fertility") #Reshape to long format, using "Fertility" as x variable 
head(swiss_soldiers) 
    Fertility variable value 
1  80.2 Agriculture 17.0 
2  83.1 Agriculture 45.1 
3  92.5 Agriculture 39.7 
4  85.8 Agriculture 36.5 
5  76.9 Agriculture 43.5 
6  76.1 Agriculture 35.3 
ggplot(swiss_soldiers)+aes(x=Fertility, y=value, colour=variable)+geom_point()+geom_smooth(method = "lm") 
#A graph containing the individual data as points plus a linear trendline 

A graph containing the individual data as points plus a linear trendline

这样,你甚至不需要你的循环。