[英]Creating multiple plots with filter or from list - r
我有一個包含 453 行和以下列的數據框:
library(data.table)
library(dplyr)
library(ggplot2)
phrase onsets IOI Per Ratio PerMax Onset_N
<dbl> <dbl> <dbl> <dbl> <chr> <dbl> <dbl>
1 1 106. 0.413 266 1.55 3.06 1
2 1 106. 0.413 266 0.51 3.06 2
3 1 106. 0.136 266 0.86 3.06 3
4 1 106. 0.23 266 1.12 3.06 4
5 1 107. 0.299 266 1.89 3.06 5
6 1 107. 0.503 266 0 3.06 6
7 1 107. 0.503 266 0 3.06 6
8 2 108. 0.517 162 0.99 8.73 1
9 2 108. 0.161 162 0.92 8.73 2
10 2 108. 0.149 162 0.94 8.73 3
11 2 108. 0.152 162 1.12 8.73 4
我想創建多個圖,以便具有相同phrase
編號的條目在同一個圖中。 這意味着 1-7 將有一個圖,8-11 將有一個圖,等等。對於所有圖,X 是Ratio
列,Y 是Onset_N
列。
這是一個情節的例子:
plot1 <- data %>%
filter(phrase == 1)%>%
ggplot(aes(Onset_N, Ratio))+
geom_point()+
labs(x = "onsets", y = "Ratio onset vs. per", title = "1")
plot1
但是,我有大量數據 - 短語從 1:60 開始。 有沒有辦法創建一個循環,其中過濾器和標題將從 1:60 開始?
另一種方法是創建一個列表
listphrases <- split(data, data$phrase)
listphrases <- data.table(listphrases)
但是,我被困在如何從列表中繪制我需要的信息。
有什么建議么? 當然,用一個代碼保存所有圖像也很方便。
先感謝您
您可以創建一個生成繪圖的函數,例如get_phrase_plot()
,然后通過phrase
應用該函數。 這是data.table
中的一個示例
get_phrase_plot <- function(dt,phrase) {
ggplot(dt,aes(Onset_N, Ratio))+
geom_point()+
labs(x = "onsets", y = "Ratio onset vs. per", title = phrase)
}
phrase
組; 我還使用特殊的.BY
將短語值作為字符串傳遞給labs()
的title
參數setDT(data)
data[,.(plot = list(get_phrase_plot(.SD, .BY))), phrase]
輸出是一個數據表。
phrase plot
<int> <list>
1: 1 <gg[9]>
2: 2 <gg[9]>
有很多方法可以保存這些地塊; 一種方便的方法是將參數save=F
添加到函數簽名中,如果將其設置為T
,則將保存繪圖。
get_phrase_plot <- function(dt,phrase, save=F) {
plt = ggplot(dt,aes(Onset_N, Ratio))+
geom_point()+
labs(x = "onsets", y = "Ratio onset vs. per", title = phrase)
if(save) {
ggsave(filename=paste0("plot_",phrase,".png"), height=8, width=14)
}
plt
}
現在,當您調用該函數時,您可以傳遞save=T
,您將獲得每個組的一個 .png 圖(即每個phrase
)
data[,.(plot = list(get_phrase_plot(.SD, .BY, save=T))), phrase]
輸出是相同的,但您還保存了 .png 文件:
> list.files(pattern="plot_\\d")
[1] "plot_1.png" "plot_2.png"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.