如何使用for-loop在ggplot中添加图层 [英] how to add layers in ggplot using a for-loop
问题描述
我想绘制一个数据框的每一列到ggplot2中的一个单独的图层。
一层一层构建工作得很好:
df <-data.frame(x1 = c(1: 5),y1 = c(2.0,5.4,7.1,4.6,5.0),y2 = c(0.4,9.4,2.9,5.4,1.1),y3 = c(2.4,6.6,8.1,5.6,6.3))
ggplot(data = df,aes(df [,1]))+ geom_line(aes(y = df [,2]))+ geom_line(aes(y = df [,3]))
有没有办法通过使用单个函数来绘制所有可用的列?
我试图这样做,但它不起作用:
plotAllLayers< - 函数(df){
p <-ggplot(data = df,aes(df [,1]))
for(i in seq(2:ncol(df))){
p< -p + geom_line(aes(y = df [,i]))
}
return(p)
}
plotAllLayers(df)
一种方法是将数据帧从宽格式转换为使用函数 melt()
从库 reshape2
的长格式。在新数据框中,您将有 x1
值, variable
确定来自哪个列的数据,<$ c $包含所有原始的y值。
现在你可以用一个 ggplot()绘制所有的数据 / code>和
geom_line()
调用并使用变量
来为每行分别设置颜色。
library(reshape2)
df.long< -melt(df,id.vars =x1)
头(df.long)
x1变量值
1 1 y1 2.0
2 2 y1 5.4
3 3 y1 7.1
4 4 y1 4.6
5 5 y1 5.0
6 1 y2 0.4
ggplot(df.long,aes(x1,value,color = variable))+ geom_line()
names(df)[ - 1] $ p
c $ c>而不是 seq()
。这将使列名向量(第一列除外)。然后在 geom_line()
中使用 aes_string(y = i)
来按名称选择列。 b
$ b
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)
plotAllLayers(df)
I would like to plot each column of a dataframe to a separate layer in ggplot2. Building the plot layer by layer works well:
df<-data.frame(x1=c(1:5),y1=c(2.0,5.4,7.1,4.6,5.0),y2=c(0.4,9.4,2.9,5.4,1.1),y3=c(2.4,6.6,8.1,5.6,6.3))
ggplot(data=df,aes(df[,1]))+geom_line(aes(y=df[,2]))+geom_line(aes(y=df[,3]))
Is there a way to plot all available columns at ones by using a single function?
I tried to do it this way but it does not work:
plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in seq(2:ncol(df))){
p<-p+geom_line(aes(y=df[,i]))
}
return(p)
}
plotAllLayers(df)
One approach would be to reshape your data frame from wide format to long format using function melt()
from library reshape2
. In new data frame you will have x1
values, variable
that determine from which column data came, and value
that contains all original y values.
Now you can plot all data with one ggplot()
and geom_line()
call and use variable
to have for example separate color for each line.
library(reshape2)
df.long<-melt(df,id.vars="x1")
head(df.long)
x1 variable value
1 1 y1 2.0
2 2 y1 5.4
3 3 y1 7.1
4 4 y1 4.6
5 5 y1 5.0
6 1 y2 0.4
ggplot(df.long,aes(x1,value,color=variable))+geom_line()
If you really want to use for() loop (not the best way) then you should use names(df)[-1]
instead of seq()
. This will make vector of column names (except first column). Then inside geom_line()
use aes_string(y=i)
to select column by their name.
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)
}
plotAllLayers(df)
这篇关于如何使用for-loop在ggplot中添加图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!