使用 ggplot2 组合箱线图和直方图

发布于 2024-10-09 09:26:22 字数 431 浏览 0 评论 0 原文

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

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 制作此图,我们也将不胜感激。

I am trying to combine a histogram and boxplot for visualizing a continuous variable. Here is the code I have so far

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

It looks fine except for the alignment of the x axes. Can anyone tell me how I can align them?
Alternately, if someone has a better way of making this graph using ggplot2, that would be appreciated as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

拒绝两难 2024-10-16 09:26:22

你可以通过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))

you can do that by coord_cartesian() and align.plots in ggExtra.

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)

Here is a modified version of align.plot to specify the relative size of each panel:

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)
    }
}

usage:

# 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

忘东忘西忘不掉你 2024-10-16 09:26:22

使用cowplot包。

library(cowplot)

#adding xlim and ylim to align axis.
p1 = qplot(x = 1, y = mpg, data = mtcars, xlab = "", geom = 'boxplot') + 
  coord_flip() +
  ylim(min(mtcars$mpg),max(mtcars$mpg))

p2 = qplot(x = mpg, data = mtcars, geom = 'histogram')+
  xlim(min(mtcars$mpg),max(mtcars$mpg))

#result
plot_grid(p1, p2, labels = c("A", "B"), align = "v",ncol = 1)

输入图像描述这里

Using cowplot package.

library(cowplot)

#adding xlim and ylim to align axis.
p1 = qplot(x = 1, y = mpg, data = mtcars, xlab = "", geom = 'boxplot') + 
  coord_flip() +
  ylim(min(mtcars$mpg),max(mtcars$mpg))

p2 = qplot(x = mpg, data = mtcars, geom = 'histogram')+
  xlim(min(mtcars$mpg),max(mtcars$mpg))

#result
plot_grid(p1, p2, labels = c("A", "B"), align = "v",ncol = 1)

enter image description here

凉城凉梦凉人心 2024-10-16 09:26:22

然而,使用 ggplot2 的另一种可能的解决方案,到目前为止我不知道如何缩放两个图的高度:

require(ggplot2)
require(grid)

fig1 <- ggplot(data = mtcars, aes(x = 1, y = mpg)) +
  geom_boxplot( ) +
  coord_flip() +
  scale_y_continuous(expand = c(0,0), limit = c(10, 35))

fig2 <- ggplot(data = mtcars, aes(x = mpg)) +
  geom_histogram(binwidth = 1) +
  scale_x_continuous(expand = c(0,0), limit = c(10, 35))

grid.draw(rbind(ggplotGrob(fig1),
                ggplotGrob(fig2),
                size = "first"))

< img src="https://i.sstatic.net/IxB1L.png" alt="plot">

Another possible solution using ggplot2, however, so far I do not know how to scale the two plots in height:

require(ggplot2)
require(grid)

fig1 <- ggplot(data = mtcars, aes(x = 1, y = mpg)) +
  geom_boxplot( ) +
  coord_flip() +
  scale_y_continuous(expand = c(0,0), limit = c(10, 35))

fig2 <- ggplot(data = mtcars, aes(x = mpg)) +
  geom_histogram(binwidth = 1) +
  scale_x_continuous(expand = c(0,0), limit = c(10, 35))

grid.draw(rbind(ggplotGrob(fig1),
                ggplotGrob(fig2),
                size = "first"))

plot

一刻暧昧 2024-10-16 09:26:22

我知道的最好的解决方案是使用 ggpubr 包:

require(ggplot2)
require(ggpubr)
p1 = qplot(x = 1, y = mpg, data = mtcars, xlab = "", geom = 'boxplot') + 
     coord_flip()
p2 = qplot(x = mpg, data = mtcars, geom = 'histogram')
ggarrange(p2, p1, heights = c(2, 1), align = "hv", ncol = 1, nrow = 2)

在此处输入图像描述

The best solution I know is using the ggpubr package:

require(ggplot2)
require(ggpubr)
p1 = qplot(x = 1, y = mpg, data = mtcars, xlab = "", geom = 'boxplot') + 
     coord_flip()
p2 = qplot(x = mpg, data = mtcars, geom = 'histogram')
ggarrange(p2, p1, heights = c(2, 1), align = "hv", ncol = 1, nrow = 2)

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文