2

我想boxplot在直方图下方放置一个。我已经想出了如何做到这一点,但是boxplot和直方图大小相同,我想缩小boxplot. 当我减小宽度时,边缘的空间保持不变。但是,我想减小整个事物的宽度。

这是我到目前为止所拥有的:

library(ggplot2)
h = ggplot(mtcars, aes(x=hp)) +
  geom_histogram(aes(y = ..density..)) +
  scale_x_continuous(breaks=c(100, 200, 300), limits=c(0,400)) +
  geom_density(, linetype="dotted")

b <- ggplot(mtcars,aes(x=factor(0),hp))+geom_boxplot(width=0.1) +
  coord_flip(ylim=c(0,400)) +
  scale_y_continuous(breaks=c(100, 200, 300)) +
  theme(axis.title.y=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank())

library(gridExtra)
plots <- list(h, b)
grobs <- list()
widths <- list()
for (i in 1:length(plots)){
  grobs[[i]] <- ggplotGrob(plots[[i]])
  widths[[i]] <- grobs[[i]]$widths[2:5]
}
maxwidth <- do.call(grid::unit.pmax, widths)
for (i in 1:length(grobs)){
  grobs[[i]]$widths[2:5] <- as.list(maxwidth)
}
do.call("grid.arrange", c(grobs, ncol=1))

历史+箱线图

编辑:
如果我像这样使用 grid.arrange() :

grid.arrange(heights=c(4,1), h, b)

在此处输入图像描述

比例与我想要的完全一样,但我无法弄清楚如何调整上面的第一个示例,以使轴再次对齐。

任何人?

4

1 回答 1

1

您只需要在调用中使用宽度校正的 grobs,而不是原始图grid.arrange

grid.arrange(heights = c(4, 1), grobs[[1]], grobs[[2]])
于 2014-03-31T01:33:44.003 回答