以固定的列间隔在数据框中绘制多个数据,并在R中使用ggplot2在相同的图中绘制相应的图例 [英] Plotting multiple data in a data frame at fixed column intervals with corresponding legend in one single plot with ggplot2 in R

查看:295
本文介绍了以固定的列间隔在数据框中绘制多个数据,并在R中使用ggplot2在相同的图中绘制相应的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码生成了30列的数据框 x3 ,我想在单个图中绘制第一列为x轴,y-轴应该是列5,10,15,20,25和30。

  x < -  c(1:10) 
y < - x ^ 3
z < - y-20
s < - z / 3
t < - s * 6
q < - s * y
x1 < - cbind(x,y,z,s,t,q)
x2 < - cbind(x1,x1 * 5)
x3 < - cbind(x1, x1 * 5,x2 * 2,x1 + 2)
x3 < - data.frame(x3)

为了绘制多个y数据(列5,10,15,20,25和30)与相同的x轴数据,我使用下面这段代码:

  plt <-ggplot()+ 
lapply(seq(5,ncol(x3),5),
function(x) {
geom_line(aes(x = x3 [1],y = x3 [x]),
color = variable,
size = 1.5)+ scale_y_continuous()
})+ xlab('x')+ ylab('y')

但我在do.call中遇到了错误(layer..
有人请指出我需要在上面的代码中修改以便以适当的方式显示数据和图例。



感谢

解决方案使用 melt 将数据重塑为长格式:

  x4 < -  melt(x3,id = c(x),measure = c(t,s.1,z.2,y.3,x.4,q.4),变量=cols)

然后创建您的情节:

  ggplot(x4)+ 
geom_line(aes(x = x,y = value,color = cols),size = 1)+
scale_y_continuous()

给出:


I have a data frame x3 of 30 columns generated using the following codes, I would like to plot in a single plot the first column to be x axis and y-axis should be columns 5,10,15,20,25 and 30.

x <- c(1:10)
y <- x^3
z <- y-20
s <- z/3
t <- s*6
q <- s*y
x1 <- cbind(x,y,z,s,t,q)
x2 <- cbind(x1,x1*5)
x3 <- cbind(x1,x1*5,x2*2,x1+2)
x3 <- data.frame(x3)

To plot multiple y-data (columns 5,10,15,20,25,and 30) vs the same x-axis data, I use this following piece of code,

plt <- ggplot() + 
  lapply(seq(5,ncol(x3),5),         
         function(x){              
           geom_line(aes(x=x3[1], y=x3[x]),                           
                     color=variable,                                
                     size=1.5) + scale_y_continuous()                                          
         }) +   xlab('x') +  ylab('y')

But I get error in do.call("layer" .. Could someone please point out what I need to modify in the above code to display the data in a proper manner along with the legend.

Thanks

解决方案

Use melt to reshape your data into long format:

x4 <- melt(x3, id=c("x"), measure=c("t","s.1","z.2","y.3","x.4","q.4"), variable = "cols")

Then create your plot with:

ggplot(x4) +
  geom_line(aes(x=x, y=value, color=cols), size=1) + 
  scale_y_continuous() 

which gives:

这篇关于以固定的列间隔在数据框中绘制多个数据,并在R中使用ggplot2在相同的图中绘制相应的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆