简体   繁体   中英

How to combine graph of different rows (data frame) & plot in a same graph in R?

I have 3 sets of data frame named "EPp4", "JPp4" & "USp4" of different rows. The data frame looks like this.

EPp4
Source: local data frame [37 x 3]

    Year     n     N
   (int) (int) (int)
1   1979     2     2
2   1980     3     5
3   1981     4     9
4   1982    18    27
5   1983     8    35
6   1984     4    39
7   1985     8    47
8   1986     6    53
9   1987    11    64
10  1988     2    66
..   ...   ...   ...

I wanted to plot a graph combining all three sets of df using cbind but each of them have different rows.

y <- cbind(EPp4, JPp4[,2], USp4[,2], DEp4[,2], CNp4[,2])

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 37, 23, 69

So, I have no choices but to transform it to the same no. of rows. Is there any better way to do this? Or can I plot three of them in a same graph with different rows? Appreciate for any help.

EPp5 <- EPp4[15:37,1:2]
USp5 <- USp4[47:69,1:2]
JPp5 <- JPp4[,1:2]
y <- cbind(EPp5, JPp5[,2], USp5[,2])

g <- ggplot(y, aes(Year))
g <- g + geom_line(aes(y=n1), colour="green")
g <- g + geom_line(aes(y=n2), colour="red")
g <- g + geom_line(aes(y=n3), colour="blue")
g <- g + ylab("Counts") + xlab("Year")

You can specify for each geom an own dataset.

library(ggplot2)

df1<-data.frame(x=1:20,y=1:20)
df2<-data.frame(x=1:10, y=11:20)

ggplot()+geom_line(aes(x=x,y=y), data = df1)+geom_line(aes(x=x,y=y), data = df2)

在此处输入图片说明

*edit

Adding Heroka's answer (I hope that is ok Heroka?)

#adding id
df1<-data.frame(df1, id = rep("a", nrow(df1)))
df2<-data.frame(df2, id = rep("b", nrow(df2)))

df<-rbind(df1,df2)


ggplot(data = df)+geom_line(aes(x=x,y=y,color = id))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM