R 直方图和箱线图对齐

标签 r layout histogram bar-chart par

我有一个问题,我想将条形图放在直方图下,其中一个值的条形图恰好在直方图的特定值下方。不幸的是,直方图的缩放比例与条形图中的不同,而且直方图中还有一点间隙。

是否有可能重新安排?

# data
set.seed(4566)
a <- rnorm(100)
a <- dnorm(a)*10+1 
data <- a

#data plot 2
values <- matrix(,,3)
values[1,1] <- 1
values[1,2] <- 2
values[1,3] <- 3
colnames(values) <- c('Mean','Best 50%','Worst 50%')

# layout boxplot is at the bottom 
nf <- layout(mat = matrix(c(1,2),2,1, byrow=TRUE), height = c(3,1))
par(mar=c(3.1, 3.1, 1.1, 2.1),oma=c(0,2,1,1))
b <- c(0,1,2,3,4,5)
hist(data,xlim = range(0:6),ylim=range(0:25),col = "blue",breaks=b)
barplot(values, horiz=T, xlim=range(0:6),ylim=range(0:3),las=1)

enter image description here

最佳答案

一种方法是在 hist 调用中使用 xaxs 参数

nf <- layout(mat = matrix(c(1,2),2,1, byrow=TRUE), height = c(3,1))
par(mar=c(3.1, 3.1, 1.1, 2.1),oma=c(0,2,1,1))
hist(data,xlim = range(0:6),ylim=range(0:25),col = "blue", breaks=b, xaxs="i")
barplot(values, horiz=T, xlim=range(0:6),ylim=range(0:3), las=1)

给出

enter image description here

xaxs 参数用于计算 x 轴(参见 ?par)。

看看它做了什么

默认的xaxs = "r"

hist(data,xlim = range(0:6),ylim=range(0:25),col = "blue", breaks=b, xaxs="r")
par("usr")
#[1] -0.24  6.24 -1.00 26.00

前两点给出了 x 轴限制 - 您可以看到它已经扩展。 要强制使其保持在数据范围内,您可以使用 xaxs="i" 选项

hist(data,xlim = range(0:6),ylim=range(0:25),col = "blue", breaks=b, xaxs="i")
par("usr")
#[1]  0  6 -1 26

这与你的条形图一致

barplot(values, horiz=T, xlim=range(0:6),ylim=range(0:3), las=1)
par("usr")
#[1]  0.00  6.00 -0.12  3.12

关于R 直方图和箱线图对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323802/

相关文章:

r - 转换堆积密度图中每个因子的高度 (ggplot2)

html - 如何使用 rvest 收集此表中的所有 url?

r - 为什么 get 在 gamm 中找不到对象,但在 lm 中却可以?

html - 如何防止 HTML 元素在浏览器调整大小时移动?

html - 滚动条在div后面

java - 将 double 分组到映射以创建直方图

r - 如何在 PostgreSQL 中显示主机、用户和端口

Java - 不知道要使用哪种布局?

python - 如何向 Seaborn 分布图添加均值线和中线

c# - C#中整数数据的简单直方图生成