r - 使用 ggplot2 组合 Boxplot 和 Histogram

标签 r ggplot2 histogram boxplot

我正在尝试结合直方图和箱线图来可视化连续变量。这是我到目前为止的代码

require(ggplot2)
require(gridExtra)
p1 = qplot(x = 1, y = mpg, data = mtcars, xlab = "", geom = 'boxplot') + 
     coord_flip()
p2 = qplot(x = mpg, data = mtcars, geom = 'histogram')
grid.arrange(p2, p1, widths = c(1, 2))

plot

除了 x 轴的对齐之外,它看起来很好。谁能告诉我如何对齐它们?
或者,如果有人有更好的方法使用 ggplot2 制作此图,那也将不胜感激。

最佳答案

你可以通过 ggExtra 中的 coord_cartesian() 和 align.plots 来做到这一点。

library(ggplot2)
library(ggExtra) # from R-forge

p1 <- qplot(x = 1, y = mpg, data = mtcars, xlab = "", geom = 'boxplot') + 
  coord_flip(ylim=c(10,35), wise=TRUE)
p2 <- qplot(x = mpg, data = mtcars, geom = 'histogram') + 
  coord_cartesian(xlim=c(10,35), wise=TRUE)

align.plots(p1, p2)

这是 align.plot 的修改版本,用于指定每个面板的相对大小:
align.plots2 <- function (..., vertical = TRUE, pos = NULL) 
{
    dots <- list(...)
    if (is.null(pos)) pos <- lapply(seq(dots), I)
    dots <- lapply(dots, ggplotGrob)
    ytitles <- lapply(dots, function(.g) editGrob(getGrob(.g, 
        "axis.title.y.text", grep = TRUE), vp = NULL))
    ylabels <- lapply(dots, function(.g) editGrob(getGrob(.g, 
        "axis.text.y.text", grep = TRUE), vp = NULL))
    legends <- lapply(dots, function(.g) if (!is.null(.g$children$legends)) 
        editGrob(.g$children$legends, vp = NULL)
    else ggplot2:::.zeroGrob)
    gl <- grid.layout(nrow = do.call(max,pos))
    vp <- viewport(layout = gl)
    pushViewport(vp)
    widths.left <- mapply(`+`, e1 = lapply(ytitles, grobWidth), 
        e2 = lapply(ylabels, grobWidth), SIMPLIFY = F)
    widths.right <- lapply(legends, function(g) grobWidth(g) + 
        if (is.zero(g)) 
            unit(0, "lines")
        else unit(0.5, "lines"))
    widths.left.max <- max(do.call(unit.c, widths.left))
    widths.right.max <- max(do.call(unit.c, widths.right))
    for (ii in seq_along(dots)) {
        pushViewport(viewport(layout.pos.row = pos[[ii]]))
        pushViewport(viewport(x = unit(0, "npc") + widths.left.max - 
            widths.left[[ii]], width = unit(1, "npc") - widths.left.max + 
            widths.left[[ii]] - widths.right.max + widths.right[[ii]], 
            just = "left"))
        grid.draw(dots[[ii]])
        upViewport(2)
    }
}

用法:
# 5 rows, with 1 for p1 and 2-5 for p2
align.plots2(p1, p2, pos=list(1,2:5))
# 5 rows, with 1-2 for p1 and 3-5 for p2
align.plots2(p1, p2, pos=list(1:2,3:5))

align.plots2 second example

关于r - 使用 ggplot2 组合 Boxplot 和 Histogram,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4551582/

相关文章:

r - 从嵌套的 SpatialPolygonsDataFrame 中提取父多边形或从父多边形中提取 'Dissolving' 孔

r - "parse"和 "expression"之间的区别

r - 如何在 GGPLOT 中的 geom_jitter() 上添加 geom_smooth() 或 stat_smooth()

python - 有没有一种干净的方法可以在 Python 中生成折线直方图?

python - matplotlib hist() 自动裁剪范围

python - matplotlib 中的多步直方图

r - 如何使用 R 在 Postgresql 中编写此 json 对象

r - 整个数据集的回归线,以及基于R ggplot2中基于组的回归线?

r - 如何更改ggplot2中图例文本的大小?

r - ggplot2 - 添加 alpha 参数使 PDF 中的所有其他文本变暗/加粗