【问题标题】:Scatter plot of two different data frames r两个不同数据帧的散点图 r
【发布时间】:2013-11-11 15:39:24
【问题描述】:

我对 R 很陌生,搜索了很多,但找不到这个问题的答案。

我有两个格式完全相同的数据框,其中行等于国家,列等于年份。我想创建一个散点图,其中数据框 1 为 X,数据框 2 为 Y。

例如:

 Data frame 1:

        1991  1992
 USA       1     3
 Canada    4     5


 Data frame 2:

        1991  1992
 USA     200   129
 Canada  245   342

对我应该怎样做有什么建议吗?

【问题讨论】:

  • “数据框 1 是 X,数据框 2 是 Y”是什么意思,x=c(1,4,3,5) vs y=c(200,245,129,342)

标签: r ggplot2


【解决方案1】:

如果我猜对了,这可能就是您要找的。只需添加一个 geom_point() 图层来绘制来自第二个数据帧的数据:

#Create dataframe A
a.country <- rep(c("USA", "Canada"), 2)
a.value   <- as.numeric(c(1, 4, 3, 5))
a.year    <- c("1991", "1991", "1992", "1992")
dtframe.a <- data.frame(a.country, a.year, a.value)

#Create dataframe B
b.country <- rep(c("USA", "Canada"), 2)
b.value   <- c(200, 245, 129, 342)
b.year    <- c("1991", "1991", "1992", "1992")
dtframe.b <- data.frame(b.country, b.year, b.value)

# Use ggplot2 to plot data from 2 dataframes
require(ggplot2)

ggplot() +
  geom_point(data=dtframe.a, aes(a.year, a.value, color= a.country)) +
  geom_point(data=dtframe.b, aes(b.year, b.value, color= b.country))

【讨论】:

    【解决方案2】:

    我知道的大多数散点图命令在同一数据框中使用不同的列。我建议将您的两个数据框合并为一个。目前尚不清楚您是将 1991 年和 1992 年的值一起绘制还是分开绘制,所以我关注 DanielRP 并假设您将它们绘制在一起(但在散点图中)。您可以在绘图中将年份作为条件来分别绘制它们。这是一个希望能帮助您入门的示例:

    #Create dataframe 1
    country <- rep(c("USA", "Canada"), 2)
    x.value   <- as.numeric(c(1, 4, 3, 5))
    year    <- c("1991", "1991", "1992", "1992")
    df.1 <- data.frame(country, year, x.value)
    
    #Create dataframe 2
    country <- rep(c("USA", "Canada"), 2)
    y.value   <- c(200, 245, 129, 342)
    year    <- c("1991", "1991", "1992", "1992")
    df.2 <- data.frame(country, year, y.value)
    
    #Merge the two dataframes based on 'country' (since this is identical in both)
    new.df<-merge(df.1,df.2)
    
    #Make your scatterplot
    plot(new.df$x.value,new.df$y.value,xlab="X value",ylab="Y value")
    

    这是一个非常简单的情节,因此根据您的需要,您可能更喜欢使用 ggplot2 或其他包。

    【讨论】:

    • 其实这里不需要合并。 plot(df.1$x.value,df.2$y.value,xlab="X value",ylab="Y value") 也可以,因为您将两个数值向量传递给 plot 函数。不过,ggplot 需要相同的数据框。
    猜你喜欢
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多