以固定的列间隔在一个数据框中绘制多个数据,并在一个图中绘制相应的图例 [英] Plotting multiple data in a data frame at fixed column intervals with corresponding legend in one single plot
问题描述
我有一个使用以下代码生成的30列的数据框x3
,我想在一个图中绘制第一列为x轴,y轴为5,10,15,20列,25和30.
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)
要绘制多个y数据(第5、10、15、20、25和30列)与相同的x轴数据,我使用以下代码,
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')
但是我在do.call("layer" .. 有人可以指出我需要在上面的代码中进行哪些修改,以便以正确的方式显示数据以及图例.
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.
谢谢
推荐答案
使用melt
将数据重整为长格式:
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()
给出:
这篇关于以固定的列间隔在一个数据框中绘制多个数据,并在一个图中绘制相应的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!