我想为每个图添加一个标签,理想情况下标签应该放置在顶部和x轴的中心位置,下面是示例:
ggplot2::ggplot(mtcars) +
ggplot2::geom_point(ggplot2::aes(mpg, wt)) +
ggplot2::geom_smooth(ggplot2::aes(mpg, wt)) +
ggplot2::scale_y_continuous(labels = function(x) paste0(x, " very very long label")) +
ggplot2::labs(tag = "A", x = "mpg", y = "wt") +
ggplot2::theme(plot.tag.position = "top")
我注意到,当 y 轴标签很长时,标签看起来位于整个面板的中心,而不是 x 轴的中心。我该如何修复它?
最佳答案
如果您不使用映射到数据的构面,则可以创建一个具有固定值的假构面,并使用strip.background
对其进行样式设置。 theme
元素:
ggplot(mtcars) +
geom_point(aes(mpg, wt)) +
geom_smooth(aes(mpg, wt)) +
scale_y_continuous(labels = function(x) paste0(x, " very very long label")) +
facet_wrap(~ "A") +
labs(x = "mpg", y = "wt") +
theme(strip.background = element_rect(fill = "white"))
可能更好的选择是添加一个没有标签也没有中断的辅助 x 轴,并通过设置 axis.line.x.top
来删除该行关于theme
至element_blank()
:
ggplot(mtcars) +
geom_point(aes(mpg, wt)) +
geom_smooth(aes(mpg, wt)) +
scale_y_continuous(labels = function(x) paste0(x, " very very long label")) +
###
scale_x_continuous(sec.axis = dup_axis(name = "A", labels = NULL, breaks = NULL)) +
###
labs(x = "mpg", y = "wt") +
theme(axis.line.x.top = element_blank())
关于r - ggplot2标签位置不居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77731328/