【发布时间】:2022-01-20 21:48:13
【问题描述】:
我使用来自@ClausWilke 的这个非常有用的answer(转载如下)在 x 和 y 轴上生成了一个带有边缘直方图的散点图。
library(cowplot)
# Main plot
pmain <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))+
geom_point()+
ggpubr::color_palette("jco")+
theme(legend.position = c(0.8, 0.8))
# Marginal densities along x axis
xdens <- axis_canvas(pmain, axis = "x")+
geom_boxplot(data = iris, aes(x = Sepal.Length, fill = Species),
alpha = 0.7, size = 0.2)+
ggpubr::fill_palette("jco")
# Marginal densities along y axis
# Need to set coord_flip = TRUE, if you plan to use coord_flip()
ydens <- axis_canvas(pmain, axis = "y", coord_flip = TRUE)+
geom_boxplot(data = iris, aes(x = Sepal.Width, fill = Species),
alpha = 0.7, size = 0.2)+
coord_flip()+
ggpubr::fill_palette("jco")
p1 <- insert_xaxis_grob(pmain, xdens, grid::unit(.2, "null"), position = "top")
p2<- insert_yaxis_grob(p1, ydens, grid::unit(.2, "null"), position = "right")
ggdraw(p2)
这很好用,但我的下一个挑战是将此图用作图中的面板,另一个图 - geom_bar 图 - 位于右侧。我可以使用 plot_grid 将它们并排排列并使 x 轴很好地对齐,但我希望此 geom_bar 图表的高度仅匹配上一个图 p2 中散点图 (pmain) 的高度,而不是到达p2 中 x 轴直方图顶部的高度。
其他几件真正能帮助我的事情......
- 让 x 轴标题沿底行对齐的某种方式(它们目前处于关闭状态,因为我已删除条形图上的 x 轴标签)
- 能够用一点空白将两个图分开
我在下面的完整尝试...
library(cowplot)
# Main plot
pmain <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species))+
geom_point()+
ggpubr::color_palette("jco")+
theme(legend.position = c(0.8, 0.8))
# Marginal densities along x axis
xdens <- axis_canvas(pmain, axis = "x")+
geom_boxplot(data = iris, aes(x = Sepal.Length, fill = Species),
alpha = 0.7, size = 0.2)+
ggpubr::fill_palette("jco")
# Marginal densities along y axis
# Need to set coord_flip = TRUE, if you plan to use coord_flip()
ydens <- axis_canvas(pmain, axis = "y", coord_flip = TRUE)+
geom_boxplot(data = iris, aes(x = Sepal.Width, fill = Species),
alpha = 0.7, size = 0.2)+
coord_flip()+
ggpubr::fill_palette("jco")
p1 <- insert_xaxis_grob(pmain, xdens, grid::unit(.2, "null"), position = "top")
p2<- insert_yaxis_grob(p1, ydens, grid::unit(.2, "null"), position = "right")
ggdraw(p2)
# generate a separate bar chart to go alongside
petal.bar <- ggplot(data=iris, aes(y=Petal.Width, x=Species, fill = Species))+
geom_bar(stat="summary", fun="mean", position = "dodge")+
theme(axis.text.x = element_blank(),
legend.position = "none")+
geom_point()+
ggpubr::fill_palette("jco")
# place bar chart to the right
plot_grid(p2, petal.bar, align = "h", axis = "b", nrow = 1, rel_widths = c(1, 0.6))
任何帮助将不胜感激 - 谢谢!
【问题讨论】:
标签: r alignment axis-labels cowplot x-axis