![](/img/trans.png)
[英]R ggplot2: Not plotting the right data and geom_path not plotting
[英]Plotting individual responses for two-way repeated measures design with geom_path from ggplot2
我想使用ggplot
和geom_path
來繪制在完全平衡的雙向重復測量實驗設計中測得的各個響應。
我能夠為來自類似結構的混合模型設計的數據生成所需的圖 。
我的數據集具有類似的結構化數據。 每個數據集都有一個響應變量“ Response”和三個獨立變量。
在我的第一個數據集(DF1)中,我有“參與者”,“性別”和“條件”。 其中包括三名女性和四名男性,使“性別”成為“受試者之間”因素,而“狀況”成為“受試者內部”因素,如果我沒有記錯的話,這是混合模型設計。
DF1 <-
data.frame(
Response = c(3.2, 3.4, 3.5, 3.7, 3.2, 3.6, 3.5, 3.3, 3.3, 3.3, 3.3, 3.2, 3.4, 3.3),
Participant = as.factor(c(24, 33, 40, 24, 33, 40, 27, 30, 35, 42, 27, 30, 35, 42)),
Gender = c("female", "female", "female", "female", "female", "female", "male", "male", "male", "male", "male", "male", "male", "male"),
Condition = c("trained", "trained", "trained", "untrained", "untrained", "untrained", "untrained", "untrained", "trained", "untrained", "trained", "trained", "untrained", "trained"))
在第二個數據集(DF2)中,我有“參與者”,“時間”和“條件”。 相同的參與者參與了“時間” *“條件”的所有組合,使之成為平衡的雙向重復測量設計。
DF2 <-
data.frame(
Response = c(6.0, 6.4, 5.8, 6.3, 6.9, 6.2, 7.6, 7.2, 6.9, 7.0, 7.1, 7.1),
Participant = as.factor(c(2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4)),
Time = as.factor(c(6, 6, 6, 6, 6, 6, 18, 18, 18, 18, 18, 18)),
Condition = c("Nonexercise", "Nonexercise", "Nonexercise", "Exercise", "Exercise", "Exercise", "Nonexercise", "Nonexercise", "Nonexercise", "Exercise", "Exercise", "Exercise"))
對於我的第一個數據幀(DF1),我可以將ggplot
和geom_path
與group
和color
美學( aes
)結合使用以獲得有意義的圖。
library(ggplot2)
ggplot(DF1,
aes(x = Condition,
y = Response,
group = Participant,
color = Gender)) +
geom_path()
如果我嘗試對第二個數據幀(DF2)使用相同的設置,則會繪制數據,但是這種方式對我來說沒有意義。
ggplot(DF2,
aes(x = Time,
y = Response,
group = Participant,
color = Condition)) +
geom_path()
我可以使用facet_grid
來獲取有意義的圖,但這並不理想,因為我希望所有數據都在一個圖上,類似於在繪制DF1時可以看到的圖。
ggplot(DF2,
aes(x = Time,
y = Response,
group = Participant,
color = Participant)) +
geom_path() + facet_grid(.~Condition)
我特別想要:
在此先感謝您的任何建議!
您想按Condition
和Paticipant
分組。 一種方法是使用interaction()
函數:
library(ggplot2)
DF2 <- data.frame(
Response = c(6.0, 6.4, 5.8, 6.3, 6.9, 6.2, 7.6, 7.2, 6.9, 7.0, 7.1, 7.1),
Participant = as.factor(c(2, 3, 4, 2, 3, 4, 2, 3, 4, 2, 3, 4)),
Time = as.factor(c(6, 6, 6, 6, 6, 6, 18, 18, 18, 18, 18, 18)),
Condition = c("Nonexercise", "Nonexercise", "Nonexercise", "Exercise", "Exercise", "Exercise", "Nonexercise", "Nonexercise", "Nonexercise", "Exercise", "Exercise", "Exercise"))
ggplot(DF2) +
geom_path(aes(x = Time, y = Response, group = interaction(Condition, Participant), color = Condition)) +
geom_point(aes(x = Time, y = Response, shape = Participant, color = Condition), size = 3)
我還添加了具有不同形狀的點以提高清晰度。
這就是您的要求。 如果您對我的觀點感興趣,交換映射將進一步改善該圖(前提是其他圖中的更改保持一致):
ggplot(DF2) +
geom_path(aes(x = Time, y = Response, group = interaction(Condition, Participant), color = Participant)) +
geom_point(aes(x = Time, y = Response, shape = Condition, color = Participant), size = 3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.