[英]Conditionally plot multiple variables (grouped data) in loop in R
我已經看到了幾個條件繪圖以及分組數據問題(例如這里和這里),但我的問題是不同的。 我的dataframe
dat
有以下示例數據。 數據包含五列,即Grp (character)
、 Var (integer)
(每組不相等的行)、 Col1 (numeric)
、 Col2 (numeric)
、 Col3 (numeric)
。
Grp Var Col1 Col2 Col3
grp_1 8 46.8 50.0 50.6
grp_1 16 95.6 47.4 48.0
grp_1 24 45.1 45.6 46.4
grp_1 32 68.8 44.3 58.2
grp_1 40 44.6 52.2 44.3
grp_1 48 86.5 42.2 68.6
grp_2 40 63.2 95.6 63.0
grp_2 60 66.7 67.5 65.6
grp_2 80 69.6 70.7 67.9
grp_2 100 71.9 73.4 69.3
grp_2 120 73.8 75.7 48.0
grp_3 500 51.9 50.0 50.5
grp_3 1000 65.5 53.0 53.4
grp_3 5000 61.2 99.0 59.9
grp_3 10000 80.1 63.0 62.8
grp_3 30000 25.9 33.8 14.2
對於每個組,我想 plot 列Col1
, Col2
, Col3
(y 軸)對Var
(x 軸),並有條件地將 x 軸標題更改為Var
的“steps”,“number1”和“number2”對應於grp_1,
grp_2
和grp_3.
我在這里看到一個關於有條件地更改兩個變量標簽的相關問題,但找不到三個變量。 我需要 plot 以上幾個組的數據(都在寫入本地磁盤的單個圖和 4 個圖的網格中),所以我正在尋找有關loop
和/或function
方法的建議。 有人可以建議如何實現這一目標嗎?
我仍然不確定所需的 output,您可能應該展示您迄今為止嘗試過的內容...
d <- read.table(text =
"Grp Var Col1 Col2 Col3
grp_1 8 46.8 50.0 50.6
grp_1 16 95.6 47.4 48.0
grp_1 24 45.1 45.6 46.4
grp_1 32 68.8 44.3 58.2
grp_1 40 44.6 52.2 44.3
grp_1 48 86.5 42.2 68.6
grp_2 40 63.2 95.6 63.0
grp_2 60 66.7 67.5 65.6
grp_2 80 69.6 70.7 67.9
grp_2 100 71.9 73.4 69.3
grp_2 120 73.8 75.7 48.0
grp_3 500 51.9 50.0 50.5
grp_3 1000 65.5 53.0 53.4
grp_3 5000 61.2 99.0 59.9
grp_3 10000 80.1 63.0 62.8
grp_3 30000 25.9 33.8 14.2
", header=T
)
library(ggplot2)
library(data.table)
d <- setDT(d)
dd <- melt(d, id.vars = c("Grp", "Var"), measure.vars = patterns(col="Col") )
ggplot(dd, aes(Var, value, color=variable)) +
geom_point() +
facet_wrap(~Grp,
scales = "free",
labeller = as_labeller(c(grp_1 = "Step 1", grp_2 = "Step 2", grp_3 = "Step 3") ),
strip.position = "bottom") +
xlab(NULL) +
theme(strip.background = element_blank(),
strip.placement = "outside")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.