将两个散点图合二为一

时间:2015-12-15 10:38:04

标签: r ggplot2 reshape2

我是R.的新手。我需要结合两个散点图,绘制(x1,y1)图(x2,y2)并想在同一图中绘制它们。我该怎么做?我尝试使用以下代码。

df
    x1  y1  x2  y2
1  3.6 6.7 5.8 8.9
2 12.7 9.2 8.6 9.0
3  5.8 8.9 7.9 8.7
4   NA  NA 9.0 4.5
5   NA  NA 6.0 9.0
 x1= df$x1
 x2=df$x2
 y1=df$y1
 y2=df$y2
 d1 <- data.frame(x = x1, y = y1)
 d2 <- data.frame(x = x2, y = y2)
 library(reshape2)
 d3 <- rbind(melt(d1, id.vars = "x1") , melt(d2, id.vars = "x1"))
Error: id variables not found in data: x1
 library(ggplot2)
 ggplot(d3, aes(x1, y = value, colour = variable)) + 
+     geom_point() + labs(x = "x", y = "y")+ xlim(0,100) + ylim(0,100) +
+     scale_colour_manual(values = c("red", "blue"), labels = c("d1", "d2"))
Error in ggplot(d3, aes(x1, y = value, colour = variable)) : 
  object 'd3' not found

你的帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

x1 <- 1:5
y1 <- 11:15
x2 <- 5:1
y2 <- 11:15
df <- data.frame(x1, y1, x2, y2)

ggplot(df) + geom_point(aes(x = x1, y = y1)) + geom_point(aes(x = x2, y = y2)

Here's the basic plot that is generated