我們在df2
改變x2
列的名稱對應的列x1
的名稱df1
匹配。然後我們創建一個獨特的數據框df
與rbind
。我們使用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"))
數據
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))
關鍵字:'melt'和'ggplot2'([在中的R相同的情節劇情兩個圖表]的 –
可能的複製http://stackoverflow.com/questions/2564258/plot-two-graphs-in-same-plot-in-r) – KannarKK
@KannarKK我想,我的問題是不同的。因爲x1和x2有不同的值。我需要繪製x1對y1和x2對y2。 – alan