0

R 包:cowplot / ggplot2

用例:带有边缘直方图的散点图。

问题:对于直方图,我无法在 x 轴上添加 bin 大小或参考下级/上级间隔。没有这些直方图很难阅读。

在cowplot中,有没有办法在需要时将刻度线和相应的数据标签(在x轴上)添加到边缘图?例如,对于边缘图中的直方图

使用cowplot的基本散点图+边缘直方图

require(ggplot2)
require(cowplot)

主线剧情:

pmain <- ggplot(data = mpg, aes(x = cty, y = hwy)) + 
  geom_point() +
  xlab("City driving") +
  ylab("Highway driving") + 
  theme_grey()

边际图:

xbox <- axis_canvas(pmain, axis = "x") + 
  geom_histogram(
    data = mpg,
    aes(x = cty),
    colour = "black"
  )

组合图:

p1 <- insert_xaxis_grob(pmain, xbox, grid::unit(0.5, "in"), position = "top")

ggdraw(p1)

输出 1

但是,我希望将以下图xbox2显示为 x 轴边缘图:

xbox2.1 <- ggplot() + 
  geom_histogram(
    data = mpg,
    aes(x = cty),
    colour = "black"
  )
hist_tab <- ggplot_build(xbox2.1)$data[[1]]

xbox2 <- xbox2.1 +
  scale_x_continuous(
    breaks = c(round(hist_tab$xmin,1),
               round(hist_tab$xmax[length(hist_tab$xmax)],1))
  ) +
  labs(x = NULL, y = NULL) + 
  theme(
    axis.text.x = element_text(angle = 90, size=7,vjust=0.5),
    axis.line = element_blank(),
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank()
  )

xbox2

输出 2

但我无法创建散点图 + 边缘直方图(xbox2)。我得到与第一个相同的情节:

p2 <- insert_xaxis_grob(pmain, xbox2, grid::unit(0.5, "in"), position = "top")
ggdraw(p2)

输出 3

4

1 回答 1

3

包作者在这里。您所看到的是记录在案的行为。从 的grob论点的文档中insert_xaxis_grob()

要插入的 grob。这通常是通过get_panel()从一个ggplot2对象获得的,特别是一个用 生成的对象axis_canvas()。如果ggplot2提供了绘图而不是 grob,则get_panel()调用 then 以提取面板 grob。

此功能特别不用于堆叠图。您可以将整个情节变成一个 grob,然后使用此功能插入,但我不确定这是否有意义。您尝试做的相当于堆叠两个具有相同 x 轴范围的图。我认为最好像这样明确地编码。

library(cowplot)

xlimits <- c(6, 38)

pmain <- ggplot(data = mpg, aes(x = cty, y = hwy)) + 
  geom_point() +
  xlab("City driving") +
  ylab("Highway driving") + 
  scale_x_continuous(limits = xlimits, expand = c(0, 0)) +
  theme_grey() +
  theme(plot.margin = margin(0, 5.5, 5.5, 5.5))


xhist <- ggplot() + 
  geom_histogram(
    data = mpg,
    aes(x = cty),
    colour = "black",
    binwidth = 1,
    center = 10
  ) +
  scale_x_continuous(limits = xlimits, expand = c(0, 0), breaks = 8:35) +
  labs(x = NULL, y = NULL) + 
  theme(
    axis.text.x = element_text(angle = 90, size=7, vjust=0.5),
    axis.line = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    plot.margin = margin(5.5, 5.5, 0, 5.5)
  )

plot_grid(xhist, pmain, ncol = 1, align = "v", rel_heights = c(0.2, 1))

在此处输入图像描述

于 2017-12-16T16:24:11.360 回答