使用for循环时,第一个boxplot中缺少标题

时间:2016-05-22 14:51:47

标签: r boxplot

我试图使用for循环绘制16个箱图。我的问题是,第二个标题绘制在第一个绘图上,第三个标题绘制在第二个绘图上,依此类推。

有没有人猜测,我做错了什么?

enter image description here

我的代码如下:

boxplot(data$distance[data$countryname=="Sweden"]~data$alliance[data$countryname=="Sweden"],title(main = "Sweden"))
boxplot(data$distance[data$countryname=="Norway"]~data$alliance[data$countryname=="Norway"],title(main = "Norway"))
boxplot(data$distance[data$countryname=="Denmark"]~data$alliance[data$countryname=="Denmark"],title(main = "Denmark"))
boxplot(data$distance[data$countryname=="Finland"]~data$alliance[data$countryname=="Finland"],title(main = "Finland"))
boxplot(data$distance[data$countryname=="Iceland"]~data$alliance[data$countryname=="Iceland"],title(main = "Iceland"))
boxplot(data$distance[data$countryname=="Belgium"]~data$alliance[data$countryname=="Belgium"],title(main = "Belgium"))
boxplot(data$distance[data$countryname=="Netherlands"]~data$alliance[data$countryname=="Netherlands"],title(main = "Netherlands"))
boxplot(data$distance[data$countryname=="Luxembourg"]~data$alliance[data$countryname=="Luxembourg"],title(main = "Luxembourg"))
boxplot(data$distance[data$countryname=="France"]~data$alliance[data$countryname=="France"],title(main = "France"))
boxplot(data$distance[data$countryname=="Italy"]~data$alliance[data$countryname=="Italy"],title(main = "Italy"))
boxplot(data$distance[data$countryname=="Spain"]~data$alliance[data$countryname=="Spain"],title(main = "Spain"))
boxplot(data$distance[data$countryname=="Portugal"]~data$alliance[data$countryname=="Portugal"],title(main = "Portugal"))
boxplot(data$distance[data$countryname=="Germany"]~data$alliance[data$countryname=="Germany"],title(main = "Germany"))
boxplot(data$distance[data$countryname=="Austria"]~data$alliance[data$countryname=="Austria"],title(main = "Austria"))
boxplot(data$distance[data$countryname=="Ireland"]~data$alliance[data$countryname=="Ireland"],title(main = "Ireland"))
boxplot(data$distance[data$countryname=="UK"]~data$alliance[data$countryname=="UK"],title(main = "UK"))

2 个答案:

答案 0 :(得分:1)

我认为这可以替换你的所有行修复你的问题:

for (i in data$countryname)
  boxplot(distance~alliance, subset(data, countryname==i), main=i)

但如果没有reproducible example或部分data.frame,则很难验证。

答案 1 :(得分:0)

根据documentation,您应该通过显式调用函数title()为您的箱图指定标题,而不是作为boxplot()调用中的参数。生成箱形图的前两个调用应如下所示:

boxplot(data$distance[data$countryname=="Sweden"]~data$alliance[data$countryname=="Sweden"])
title(main = "Sweden")
boxplot(data$distance[data$countryname=="Norway"]~data$alliance[data$countryname=="Norway"])
title(main = "Norway")