![](/img/trans.png)
[英]How can I create multiple plots, each with different y axis labels and titles using a for loop in R?
[英]Change titles for each subplot using loop in R
我正在嘗試使用R中的循環更改每個子圖的標題。我知道這里有一個類似的問題,但我無法在我的情況下應用這個。 這是我的數據和代碼:
# Pet size data and their names
color <- c('W', 'B', 'G', 'W', 'B', 'G', 'W', 'B', 'G', 'W', 'B', 'G', 'W', 'B', 'G', 'W', 'B', 'G')
mass <- c(10, 14, 20, 11, 16, 13, 11, 15, 10, 14, 23, 18, 12, 22, 20, 13, 14, 17)
name <- c('B', 'B', 'B', 'F', 'F', 'F', 'D', 'D', 'D', 'A', 'A', 'A', 'C', 'C', 'C', 'E', 'E', 'E')
# Make it into data frame
pet.stats <- data.frame(color, mass, name)
# Name of pets (I want to plot them by type of pets)
kitty <- c('A', 'B', 'C')
bunny <- c('D', 'E', 'F')
all.pets <- append(kitty, bunny)
all.pets <- as.factor(all.pets)
par(mfrow = c(2, 3), mar = c(4, 4, 2, 1), oma = c(0.5, 0.5, 0.5, 0.5), mgp = c(2.2, 0.7, 0))
# Loop through pet names and give title with pet type and pet name for each subplot
for (i in 1: nlevels(pet.stats$name)) {
barplot(pet.stats$mass[pet.stats$name == levels(pet.stats$name)[i]],
main = substitute(paste('Size of ', bold('lovely'),
ifelse(pet.stats$name[i] %in% kitty, 'kitty', 'bunny'),
' (', levels(pet.stats$name[i]), ')')),
xlab = 'Color', ylab = 'Mass', names = c('White', 'Black', 'Gray'))
abline(h = 0)
}
這就是我得到的:
我希望每個子情節都有一個標題“ 可愛的大小(寵物類型)(寵物名稱)”,例如“ 可愛小兔子的大小'D'”
有人可以幫我解決我做錯了什么嗎? 謝謝。
好的,所以這是你的解決方案。 問題在於R和非標准評估。 substitute
功能是凍結功能評估。 獲得所需行為的方法是在env
變量中指定您需要評估的內容。
注意,我打破了每個變量,然后在main
構造它們。 這樣可以更容易地看到發生了什么。
# Pet size data and their names
color <- c('W', 'B', 'G', 'W', 'B', 'G',
'W', 'B', 'G', 'W', 'B', 'G',
'W', 'B', 'G', 'W', 'B', 'G')
mass <- c(10, 14, 20, 11, 16, 13, 11, 15,
10, 14, 23, 18, 12, 22, 20, 13, 14, 17)
name <- c('B', 'B', 'B', 'F', 'F', 'F', 'D',
'D', 'D', 'A', 'A', 'A', 'C', 'C',
'C', 'E', 'E', 'E')
# Make it into data frame
pet.stats <- data.frame(color, mass, name)
# Name of pets (I want to plot them by type of pets)
kitty <- c('A', 'B', 'C')
bunny <- c('D', 'E', 'F')
all.pets <- append(kitty, bunny)
all.pets <- as.factor(all.pets)
現在請注意傳遞給substitute
的變量列表
par(mfrow = c(2, 3), mar = c(4, 4, 2, 1), oma = c(0.5, 0.5, 0.5, 0.5), mgp = c(2.2, 0.7, 0))
# Loop through pet names and give title with pet type and pet name for each subplot
for (i in 1: nlevels(pet.stats$name)) {
# Break out the names
animal_type <- ifelse(pet.stats$name[i] %in% kitty, 'kitty', 'bunny')
animal_names <- levels(pet.stats$name)[i]
barplot(pet.stats$mass[pet.stats$name == levels(pet.stats$name)[i]],
main = substitute(paste('Size of ', bold('lovely'),
animal_type,
' (', animal_names, ')'),
env = list(animal_type = animal_type,
animal_names = animal_names)),
xlab = 'Color', ylab = 'Mass', names = c('White', 'Black', 'Gray'))
abline(h = 0)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.