【发布时间】:2021-01-22 22:07:34
【问题描述】:
我正在使用 base R 创建多个并排的条形图(我更喜欢避免使用 ggplot,因为我经常在功能上受到限制)。我发现结果在视觉上并不令人愉悦,因为轴刻度根本不对齐:有时轴的顶部远低于最大值,有时高于最大值。有没有办法设置它,使最终的轴刻度值包括最大值?它不能完美对齐,因为每个图表都有自己的范围,因此有自己的刻度值集,但我希望至少有它,以便样式在 12 个图表中保持一致。
我正在使用函数(和循环)创建系列,因此我更喜欢自动化解决方案(而不是通过单独设置最大限制 axis() 来调整每个图表)
这是一个带有iris 数据集的简化示例。出现的问题是,第一个面板中的轴在 6 处结束,低于包括误差线 (7.2238) 在内的最大值,而在第二个面板中,轴结束于最大值之上。
library(vegan)
data(iris)
x1_mean<-tapply(iris$Sepal.Length, iris$Species, FUN=mean)
x1_sd<-tapply(iris$Sepal.Length, iris$Species, FUN=sd)
x2_mean<-tapply(iris$Petal.Width, iris$Species, FUN=mean)
x2_sd<-tapply(iris$Petal.Width, iris$Species, FUN=sd)
par(mfrow=c(1,2))
br1=barplot(x1_mean, ylim=c(0, (max(x1_mean)+max(x1_sd))*1.1))
errbar(x = br1, y = x1_mean,
yplus = x1_mean+x1_sd,
yminus = x1_mean-x1_sd, add = T, cex = 0)
br2=barplot(x2_mean, ylim=c(0, (max(x2_mean)+max(x2_sd))*1.1))
errbar(x = br2, y = x2_mean,
yplus = x2_mean+x2_sd,
yminus = x2_mean-x2_sd, add = T, cex = 0)
编辑/进展:
我已经设法使用par("yaxp") 提取了轴的最大值,并用它来添加一个额外的刻度,以便最后一个刻度值大于图表上的最大值。但是,它迫使我实际绘制默认图,它创建了两个图。
我还包含了我正在尝试构建的函数的简化版本(使用iris 作为示例数据集),这可能更清楚我的目标。
library(vegan)
data(iris)
barplot_adjust<- function(data, metric,...) {
x_means<-tapply(data[,metric], list(data$Species), FUN=mean)
x_sd<-tapply(data[,metric], list(data$Species), FUN=sd)
br1 <- barplot(height = x_means, names.arg = names(x_sd), ylim = c(0, (max(x_means+x_sd))*1.1),
main=metric, las=0,plot=TRUE,
...)
if( par("yaxp")[2]<(max(x_means+x_sd))*1.1 )
{ymx=par("yaxp")[2]+par("yaxp")[2]/par("yaxp")[3]}else{ymx=par("yaxp")[2]}
br1 <- barplot(height = x_means, names.arg = names(x_sd), ylim = c(0, ymx),
main=metric, las=0,plot=TRUE,
...)
print(ymx)
errbar(x = br1, y = x_means, yplus = x_means+x_sd, yminus = x_means-x_sd, add = T, cex = 0)
}
par(mfrow=c(2,2))
barplot_adjust(data=iris, metric="Sepal.Length")
barplot_adjust(data=iris, metric="Petal.Width")
【问题讨论】: