【问题标题】:How to combine graph of different rows (data frame) & plot in a same graph in R?如何组合不同行的图(数据框)并在 R 中的同一个图中绘制?
【发布时间】:2015-10-27 07:00:45
【问题描述】:

我有 3 组名为“EPp4”、“JPp4”和“USp4”的不同行的数据框。数据框如下所示。

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
..   ...   ...   ...

我想使用 cbind 绘制一个组合所有三组 df 的图表,但它们中的每一个都有不同的行。

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

所以,我别无选择,只能将其转换为相同的 no。的行。有没有更好的方法来做到这一点?或者我可以将其中三个绘制在具有不同行的同一张图中吗?感谢您的帮助。

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")

【问题讨论】:

  • 一般来说,ggplot 对长数据效果更好。为什么不给每个数据集添加一个标识符,rbind 他们一起,然后使用 aes 生成颜色映射和图例?

标签: r plot ggplot2 dataframe cbind


【解决方案1】:

您可以为每个几何图形指定一个自己的数据集。

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)

*编辑

添加 Herka 的答案(希望 Herka 可以吗?)

#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))

【讨论】:

  • 这很有帮助 :) 谢谢你们俩。 @heroka
猜你喜欢
  • 1970-01-01
  • 2021-10-29
  • 2020-07-23
  • 2019-06-12
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
相关资源
最近更新 更多