Cowplot:如何将刻度线和相应的数据标签添加到边缘图?

Cowplot: How to add tick marks and corresponding data labels to a marginal plot?

R Packages: cowplot / ggplot2

Use Case: Scatter plot with marginal histograms.

Issue: For histograms, I can't add bin sizes or reference lower/ upper class intervals in the x-axis. Without these histograms are difficult to read.

In cowplot, is there any way to add tick marks and corresponding data labels (in x-axis) to marginal plots, when required? E.g. for histograms in marginal plots

使用 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)

但是,我希望将以下图 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

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

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

包作者在这里。您看到的是记录在案的行为。来自 insert_xaxis_grob()grob 参数的文档:

The grob to insert. This will generally have been obtained via get_panel() from a ggplot2 object, in particular one generated with axis_canvas(). If a ggplot2 plot is provided instead of a grob, then get_panel() is called to extract the panel 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))