我有一個包含兩組的資料集 - 實驗組和控制組。每個參與者每組貢獻兩個回應,代表不同的學習方式。這些在下面帶有抖動的箱形圖中表示。我想使用 ggplot 將每個參與者的兩個回應與線條連接起來(因此對照組中的每條紅線都對應于對照組中的每條綠松石線),但是我不知道如何在條件下做到這一點。有人可以幫忙嗎?我是 R 新手,真的需要指導。
然后,如果增加 = TRUE,我需要將條件內線條的顏色更改為黑色,如果增加 = FALSE,我需要將線條的顏色更改為紅色。
理想情況下,我需要它看起來像 Jon 的示例,但使用基于 True 或 False 的黑色或紅色線條:Connecting grouped points with lines in ggplot
資料和 ggplot 如下所示:
d <- data.frame (
Subject = c("1", "2", "3", "4"),
Group = c("Exp", "Exp", "Control", "Control"),
Tr = c("14", "11", "4", "23"),
Sr = c("56", "78", "12", "10"),
Increase = c("TRUE", "TRUE", "TRUE", "FALSE")
)
# put the data in long format
d <- d %>%
gather(key = "Strategy", value = "raw", Tr, Sr)
d %>%
ggplot(aes(x = Group, y = raw, color = Strategy))
geom_boxplot(width = 0.5, lwd = 0.5)
geom_jitter(width = 0.15)
geom_line(aes(group = raw),
color = "grey",
arrow = arrow(type = "closed",
length = unit(0.075, "inches")))
uj5u.com熱心網友回復:
靈感來自您鏈接到的答案- @Jon 的答案
有幾個關鍵的事情要理解解決方案
- 由于您需要連接點和線,因此您需要它們都應用完全相同的隨機抖動,或者最好在資料進入繪圖之前抖動資料,這就是我所做的。
- 由于要應用抖動的變數不是數字,因此請注意 R 將字符向量繪制
Group為一個因子,解釋為數字 1,2,3,.. 對應于因子級別。因此,我們創建了一個數值向量 group_jit,其值在 1 和 2 左右,其偏移量基于著色變數Strategy,在 1 和 2 左右略微左右移動。 - 由于您有兩個獨立的色標,因此最好將組表示為
fill,將線條表示為colour,以避免單個圖例上有 4 個東西。
這是代碼 -
library(tidyverse)
# Load data
d <- data.frame (
Subject = c("1", "2", "3", "4"),
Group = c("Exp", "Exp", "Control", "Control"),
Tr = c("14", "11", "4", "23"),
Sr = c("56", "78", "12", "10"),
Increase = c("TRUE", "TRUE", "TRUE", "FALSE")
)
width_jitter <- 0.2 # 1 means full width between points
# put the data in long format
d_jit <- d %>%
gather(key = "Strategy", value = "raw", Tr, Sr) %>%
# type conversions
mutate(across(c(Group, Strategy), as_factor)) %>% # convert to factors
mutate(raw = as.numeric(raw)) %>% # make raw as numbers
# position on x axis is based on combination of Group and jittered Strategy. Mix to taste.
mutate(group_jit = as.numeric(Group) jitter(as.numeric(Strategy) - 1.5) * width_jitter * 2,
grouping = interaction(Subject, Strategy))
# plotting
d_jit %>%
ggplot(aes(x = Group, y = raw, fill = Strategy))
geom_boxplot(width = 0.5, lwd = 0.5, alpha = 0.05, show.legend = FALSE)
geom_point(aes(x = group_jit), size = 3, shape = 21)
geom_line(aes(x = group_jit,
group = Subject,
colour = Increase),
alpha = 0.5,
arrow = arrow(type = "closed",
length = unit(0.075, "inches"))
)
scale_colour_manual(values = c('red', 'black'))

由reprex 包于 2022-05-14 創建(v2.0.1)
為了完整起見,進行抖動的另一種更優雅的方法是為and命令提供一個position引數,該函式會像這樣添加隨機抖動(來源:@erocoar 的答案)geom_pointgeom_line
position = ggplot2::position_jitterdodge(dodge.width = 0.75, jitter.width = 0.3, seed = 1)
這樣資料本身不會改變,并且繪圖會處理抖動細節
jitterdodge是否閃避(x 軸變數的偏移)和抖動(彩色點的小噪聲)- 這里的
seed引數是關鍵,因為它確保為獨立呼叫它的點和線函式回傳相同的隨機值
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476669.html
上一篇:使用地圖和散點圖創建多圖
