首页 > 解决方案 > 设置轴刻度和标签以在条形图上包含最大值

问题描述

我正在使用 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")

标签: rgraphbar-chart

解决方案


像这样的东西怎么样:

library(vegan)
data(iris)

x1_mean<-tapply(iris$Sepal.Length, iris$Species, FUN=mean)
x1_sd<-tapply(iris$Sepal.Length, iris$Species, FUN=sd)
yl1 <- max((x1_mean + x1_sd))

x2_mean<-tapply(iris$Petal.Width, iris$Species, FUN=mean)
x2_sd<-tapply(iris$Petal.Width, iris$Species, FUN=sd)
yl2 <- max((x2_mean + x2_sd))


library(Hmisc)
par(mfrow=c(1,2))
br1=barplot(x1_mean, ylim=c(0, (max(x1_mean)+max(x1_sd))), axes=FALSE)
axis(2, at=round(seq(0,yl1, length=5), 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))), axes=FALSE)
axis(2, at=round(seq(0,yl2, length=5), 1))
errbar(x = br2, y = x2_mean, 
       yplus = x2_mean+x2_sd, 
       yminus = x2_mean-x2_sd, add = T, cex = 0)

在此处输入图像描述


推荐阅读