【发布时间】:2020-01-14 03:57:42
【问题描述】:
我正在尝试使用 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)
}
这就是我得到的:
我希望每个子图都有一个标题“可爱(宠物类型)(宠物名称)的大小”,例如“可爱兔子'D'的大小”
有人可以帮忙解决我做错了什么吗?谢谢。
【问题讨论】:
-
似乎
substitute()没有得到变量。作为旁注,不应该使用as.character(pet.stats$name[i]))之类的东西来获得pet name吗?否则,您将给出一个包含所有级别的向量。 -
感谢您的网址。在我发布之前我没有看到这个。