使用R中的循环更改每个子图的标题

时间:2019-09-12 09:39:04

标签: r loops plot title

我正在尝试使用R中的循环更改每个子图的标题。我知道有一个类似的问题here,但我无法在我的情况下应用。这是我的数据和代码:

# 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)
}

这就是我得到的:

enter image description here

我希望每个子图都有一个标题“ 可爱的大小(宠物类型)(宠物名)”,例如“ 可爱的兔子'D'的大小” < / p>

有人可以帮忙解决我在做什么错吗?谢谢。

1 个答案:

答案 0 :(得分:2)

好的,这就是您的解决方案。问题出在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)
}