r - ggplot2标签位置不居中

标签 r ggplot2

我想为每个图添加一个标签,理想情况下标签应该放置在顶部和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")

输出如下: enter image description here

我注意到,当 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 来删除该行关于themeelement_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/

相关文章:

r - data.table 通过函数内的引用赋值

r - 如何在 R 中使用 dplyr 执行多个左连接

R-Markdown:具有相对路径的输入和输出

r - R ggplot2 中比例的堆叠条形图按两个因素的水平分组

r - 如何排列从 for 循环创建的 ggplots

r - 如何对每个 ggplot 方面的堆栈进行排序?

r - 使用 ggplot 的连续线和虚线

r - "Loop through"data.table 计算条件平均值

r - "Could not find function"包中的错误 'caret',R

r - ggplot2 中的双箱图