我想用ggplot2把我的图X轴标签附在下面的图片里,但是我不知道怎么做,你能帮我吗?非常感谢。

发布于 2020-07-04 00:08:10
你可以在你的图上画一个矩形:
library(dplyr)
library(ggplot2)
tibble::rownames_to_column(mtcars) %>%
ggplot(aes(rowname, mpg)) +
geom_col() +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(x = "name")
grid::grid.rect(x = unit(32, "pt"), y = unit(5.5, "pt"),
height = unit(0.265, "npc"), width = unit(0.93, "npc"),
vjust = 0, hjust = 0, gp = grid::gpar(fill = NA))

然而,一种更健壮的方法是,当你重新缩放时,矩形不会相对于你的图移动,那就是将ggplot转换成grobtree,找到代表底轴区域的grob,并用rectGrob覆盖它的第一个成员( zeroGrob)。然后,可以使用grid::grid.draw绘制整个过程
library(dplyr)
library(ggplot2)
p <- tibble::rownames_to_column(mtcars) %>%
ggplot(aes(rowname, mpg)) +
geom_col() +
theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
labs(x = "name")
p2 <- ggplot_gtable(ggplot_build(p))
p2$grobs[[which(p3$layout$name == "axis-b")]]$children[[1]] <-
grid::rectGrob(gp = grid::gpar(fill = NA))
grid::grid.newpage()
grid::grid.draw(p2)

https://stackoverflow.com/questions/62718620
复制相似问题