如何从R中的Excel中的数据绘制多条线

时间:2020-01-19 22:11:23

标签: r ggplot2

我对R有点陌生,有什么方法可以将ColA绘制为X轴,将ColB绘制为y轴,将ColC绘制为X轴,将ColD绘制为y轴,依此类推。并且所有成对的cols具有相同的名称(例如,ColA = Dis和Colb = hard,ColC = Dis和COLd = hard等)。 基本上,我所做的就是将所有Dis和Hard分别从不同excel中的不同工作表合并到一个数据表中,然后以为可以用excel进行绘制,但是excel在一个图中只能显示255条曲线,大概有一千条曲线。然后我的数据集如下所示:


A B C D E F G H ...


Dis硬Dis硬Dis硬Dis硬...


1 3 4 6 9 11 15 20


3 4 6 9 11 22 25 30


,依此类推 我尝试了以下代码:

nwb1<-read.xlsx("newresult.xlsx")
nwb1<-as.data.frame(nwb1)
ggplot(data=nwb1, aes(x=displacement, y=hardness)) + geom_line() + geom_point( size=4, shape=21, fill="white")

该错误消息告诉我,“数据必须具有唯一的名称,但具有重复的列”

1 个答案:

答案 0 :(得分:1)

让我们尝试这样的事情,我没有您的数据,因此出于说明目的,我首先制作3个excel文件,每个文件都有一个列调用Dis和另一个调用:

library(openxlsx)
for(i in 1:3){
df = data.frame(Dis=1:10,hard=rpois(10,i)) 
write.xlsx(df,file=paste("file",i,".xlsx",sep=""))
}

现在,我们首先为要绘制的所有excel文件制作矢量:

fl = c("file1.xlsx","file2.xlsx","file3.xlsx")
df = lapply(fl,function(i){
x = read.xlsx(i)
x$sample=sub(".xlsx","",i)
x
})

df = do.call(rbind,df)
head(df)
  Dis hard sample
1   1    1  file1
2   2    0  file1
3   3    0  file1
4   4    2  file1
5   5    2  file1
6   6    2  file1

数据帧df是从所有excel文件连接而成的,并具有一个额外的列调用示例来表示文件的来源。如果您在读取/合并文件方面遇到更多问题,也可以在excel中制作一个这样的表。一旦您有了类似的东西,我们就会绘图:

ggplot(data=df, aes(x=Dis, y=hard,col=sample)) + geom_line() + 
geom_point( size=4, shape=21, fill="white")

enter image description here

如果您已将数据与excel合并,则会读取非常奇怪的data.frame,并且可以尝试以下操作,不推荐

values = do.call(cbind,lapply(1:5,function(i)cbind(1:10,1:10+rnorm(10))))
df = data.frame(rbind(rep(c("Dis","hard"),5),values))
colnames(df)=LETTERS[1:10]
head(df)
    A                B   C                 D   E                 F   G
1 Dis             hard Dis              hard Dis              hard Dis
2   1 1.09836250501178   1 0.350206285061174   1 0.620196066920137   1
3   2 1.81400395465058   2   4.2990376623795   2  1.00810320999903   2
4   3 3.94001753647332   3  3.32736042411927   3  3.23285030270875   3
5   4 3.93795305230344   4  4.14948397718842   4  3.88849871990867   4
6   5 5.08952019766558   5  5.18257115670042   5  4.72275692563252   5
                 H   I                J
1             hard Dis             hard
2 1.08603311982134   1 0.51876628213101
3 1.38614529438877   2 1.73020370187464
4 2.70650988128661   3 4.65143843701136
5 3.26676976653313   4 5.17606099966858
6 5.00453246607507   5 6.72671659884557

newdf = data.frame(
Dis=as.numeric(unlist(lapply(df[-1,df[1,] == "Dis"],as.character))),
hard=as.numeric(unlist(lapply(df[-1,df[1,] == "hard"],as.character))),
group = rep(1:(ncol(df)/2),each=nrow(df)-1)
)
ggplot(newdf,aes(x=Dis,y=hard,group=group))+geom_line()