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