這是我的資料的樣子。 長話短說,我想將 A 組中的 Y 值與 B 組中的相應 X 值進行散點圖,并可選擇按樣本著色。

我做了很多這樣的資料繪圖(有更多變數),但它總是在一個子集中,比如subset(data, Group=='A')or subset(data, Group=='B')。這是我需要跨組繪制的罕見情況。
情節代碼本身很簡單:
ggplot(data, aes(x=X(B), y=Y(A), color=as.factor(Sample)))
geom_point()
我意識到我的 X(B) 和 Y(A) 不起作用;這只是為了說明目標。我還假設有一種方法可以生成僅包含 X(B) 和 Y(A) 值的新資料集;當然對任何方法都持開放態度,但我更喜歡在 GGPLOT 中為實際圖表作業。這是我的可重復性資料集:
data <- structure(list(Group = c("A", "A", "A", "A", "A", "B", "B", "B",
"B", "B", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B"),
Sample = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), Point = c(1L, 2L, 3L, 4L,
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L,
5L), X = c(-3.26, -3.26, -3.26, -3.26, -3.26, -2.3624, -2.3877,
-2.6475, -3.0975, -3.1393, -3.26, -3.26, -3.26, -3.26, -3.26,
-0.6476, -0.7056, -0.7367, -0.9883, -0.9003), Y = c(22.55,
22.02, 19.41, 10.92, 8.3, 4.14, 4.42, 9.92, 9.86, 7.57, 67.94,
66.92, 70.26, 63.37, 61.85, 11.79, 10.86, 12.96, 12.44, 11.69
)), class = "data.frame", row.names = c(NA, -20L))
uj5u.com熱心網友回復:
您可以通過旋轉獲得等效的X(B)and :Y(A)
library(tidyverse)
pivoted <- data %>%
pivot_wider(names_from = Group, values_from = X:Y)
# data before pivoting
head(as_tibble(data))
# # A tibble: 6 x 5
# Group Sample Point X Y
# <chr> <int> <int> <dbl> <dbl>
# 1 A 1 1 -3.26 22.6
# 2 A 1 2 -3.26 22.0
# 3 A 1 3 -3.26 19.4
# 4 A 1 4 -3.26 10.9
# 5 A 1 5 -3.26 8.3
# 6 B 1 1 -2.36 4.14
# after pivoting
head(pivoted)
# # A tibble: 6 x 6
# Sample Point X_A X_B Y_A Y_B
# <int> <int> <dbl> <dbl> <dbl> <dbl>
# 1 1 1 -3.26 -2.36 22.6 4.14
# 2 1 2 -3.26 -2.39 22.0 4.42
# 3 1 3 -3.26 -2.65 19.4 9.92
# 4 1 4 -3.26 -3.10 10.9 9.86
# 5 1 5 -3.26 -3.14 8.3 7.57
# 6 2 1 -3.26 -0.648 67.9 11.8
然后您可以輕松地調整您的插圖代碼:
ggplot(pivoted, aes(x=X_B, y=Y_A, color=as.factor(Sample)))
geom_point()

uj5u.com熱心網友回復:
filter您可以使用和select重新排列資料框bind_cols。
library(dplyr)
library(ggplot2)
data %>%
filter(Group == "A") %>%
select(Sample, Y) %>%
bind_cols(data %>%
filter(Group == "B") %>%
select(X))
結果:
Sample Y X
1 1 22.55 -2.3624
2 1 22.02 -2.3877
3 1 19.41 -2.6475
4 1 10.92 -3.0975
5 1 8.30 -3.1393
6 2 67.94 -0.6476
7 2 66.92 -0.7056
8 2 70.26 -0.7367
9 2 63.37 -0.9883
10 2 61.85 -0.9003
然后將其傳輸到ggplot:
data %>%
filter(Group == "A") %>%
select(Sample, Y) %>%
bind_cols(data %>%
filter(Group == "B") %>%
select(X)) %>%
ggplot(aes(X, Y))
geom_point(aes(color = factor(Sample)))
結果:

uj5u.com熱心網友回復:
這是重塑資料的另一種方法。我們旋轉更長的時間以在它們自己的行上獲取 X 和 Y 值,然后我們可以過濾以僅保留來自 A 的 Y 值和來自 B 的 X 值。然后我們可以再次整形以僅具有 X 和 Y 的一行每個樣本/點組合的值。
library(dplyr)
library(tidyr)
library(ggplot)
data %>%
pivot_longer(cols=c(X,Y)) %>%
filter((Group=="A" & name=="Y") | (Group=="B" & name=="X")) %>%
pivot_wider(id=c(Sample, Point), names_from = name, values_from = value) %>%
ggplot()
aes(X,Y, color=as.factor(Sample))
geom_point()
要點是在嘗試繪制資料之前,您需要以正確的順序獲取資料。ggplot 總是假設你有“整潔”的資料。嘗試繪圖時盡量避免進行奇怪的資料操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426656.html
