2015-11-09 82 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) 
相關問題