2015-11-09 83 views
2

我有两个数据集。我想在同一散点图上绘制两个数据集。我怎样才能轻松地与R做到这一点?我感谢你的建议。在同一散点图上绘制不同的数据集

x1 y1 x2  y2 
42.39 2.1 53.05 8.4 
38.77 2.1 43.81 2.6 
44.43 2.6 42.67 2.4 
42.37 2 41.74 3.4 
48.79 3.6 42.99 2.9 
46.00 2 
53.71 2.7 
47.38 1.8 
43.75 3.1 
46.95 3.9 
+1

关键字:'melt'和'ggplot2'([在中的R相同的情节剧情两个图表]的 –

+0

可能的复制http://stackoverflow.com/questions/2564258/plot-two-graphs-in-same-plot-in-r) – KannarKK

+0

@KannarKK我想,我的问题是不同的。因为x1和x2有不同的值。我需要绘制x1对y1和x2对y2。 – alan

回答

2

我们在df2改变x2列的名称对应的列x1的名称df1匹配。然后我们创建一个独特的数据框dfrbind。我们使用reshape2包中的melt将数据转换为长格式并保留原始数据帧的标识符:df$variable。最后我们使用ggplot2和颜色来绘制散点图来区分两个数据帧。

library(reshape2) 
library(ggplot2) 
names(df2) <- c("x1", "y2") 
df <- rbind(melt(df1, id.vars = "x1"), melt(df2, id.vars = "x1")) 
ggplot(df, aes(x1, y = value, colour = variable)) + 
    geom_point() + labs(x = "x", y = "y") + 
    scale_colour_manual(values = c("red", "blue"), labels = c("df1", "df2")) 

enter image description here

数据

df1 <- structure(list(x1 = c(42.39, 38.77, 44.43, 42.37, 48.79, 46, 
53.71, 47.38, 43.75, 46.95), y1 = c(2.1, 2.1, 2.6, 2, 3.6, 2, 
2.7, 1.8, 3.1, 3.9)), .Names = c("x1", "y1"), class = "data.frame", row.names = c(NA, 
-10L)) 
df2 <- structure(list(x2 = c(53.05, 43.81, 42.67, 41.74, 42.99), y2 = c(8.4, 
2.6, 2.4, 3.4, 2.9)), .Names = c("x2", "y2"), class = "data.frame", row.names = c(NA, 
-5L)) 
1

简单的例子

set.seed(100) 
    df <- data.frame(x1 = rnorm(10, 10, 20), y1 = rnorm(10, 10, 2), x2 = rnorm(10, 10, 4), y2= rnorm(10, 10, 4)) 

    plot(df$x1, df$y1) 
    points(df$x2, df$y2, pch = 16) 
相关问题