我有以下資料框:
df1<-data.frame(id_1=c(1,2,3,4,5),
value1=c(0,0.2,0.5,0.8,0),
value2=c(0.1,0.3,0.5,0.7,0.8),
value3=c(0.5,0.6,0.3,0.2,0.1))
df2<-data.frame(id_2=c(1,2,3,4,5),
value1=c(0,0.2,0.5,0.8,0),
value2=c(0.1,0.1,0.5,0.6,0.7),
value3=c(0.4,0.4,0.8,0.9,0.2))
我想制作以下情節:
ggplot(data.frame(x=df1$value1, y=df2$value1), aes(x=x, y=y))
geom_point()
geom_point(data.frame(x=df1$value2, y=df2$value2), aes(x=x, y=y))
geom_point(data.frame(x=df1$value3, y=df2$value3), aes(x=x, y=y))
如何制作該圖而不必geom_point()為每value列復制粘貼?之后,如何找到最終重疊圖中變數的相關系數?
任何幫助將不勝感激,謝謝!
uj5u.com熱心網友回復:
您需要將資料組合到一個資料框中。這是一種方法:
## make column names the same
## and add columns indicating the data frame source
df1$var = "x"
df2$var = "y"
names(df1)[1] = "id"
names(df2)[1] = "id"
## put the data together
df = rbind(df1, df2)
## reshaped the data
library(tidyr)
df = pivot_longer(df, starts_with("value"))
df = pivot_wider(df, names_from = "var", values_from = "value")
df
# # A tibble: 15 × 4
# id name x y
# <dbl> <chr> <dbl> <dbl>
# 1 1 value1 0 0
# 2 1 value2 0.1 0.1
# 3 1 value3 0.5 0.4
# 4 2 value1 0.2 0.2
# 5 2 value2 0.3 0.1
# 6 2 value3 0.6 0.4
# 7 3 value1 0.5 0.5
# 8 3 value2 0.5 0.5
# 9 3 value3 0.3 0.8
# 10 4 value1 0.8 0.8
# 11 4 value2 0.7 0.6
# 12 4 value3 0.2 0.9
# 13 5 value1 0 0
# 14 5 value2 0.8 0.7
# 15 5 value3 0.1 0.2
一旦您的資料格式整齊,繪圖就很簡單。shape您可以使用或美學進一步自定義您的繪圖color以識別資料源。
ggplot(df, aes(x = x, y = y))
geom_point()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414690.html
標籤:
下一篇:拆分字串在R中保留空格
