当plot.margin存在ggplot2时标题右对齐

Mat*_*sko 5 r ggplot2

我想将标题推到右侧,但包括添加的边距(右侧 30 毫米)。我找不到任何有关如何执行此操作的信息。使用plot.caption = element_text(hjust = 1)内部theme()不起作用。如果可能的话我想要纯 ggplot2 解决方案。它需要在任何绘图中工作(不同的 x 限制不仅在这个绘图中)。

library(tibble)
library(ggplot2)
library(dplyr)

tibble(x = letters[1:4], n = 10*1:4, lab = " long thus margin") %>%
  ggplot(aes(reorder(x, n), n)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = lab), hjust = -0.1) +
  coord_flip(clip = "off") +
  labs(caption = "This is caption") +
  theme_minimal() +
  theme(plot.margin = unit(c(0, 30, 0, 0), "mm"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑:

目标是实现这个情节:

在此输入图像描述

Z.L*_*Lin 2

您可以在绘制绘图之前修改标题的定位位置。(从技术上讲,这是一个纯粹的 ggplot2 解决方案,因为 grob-hacking 是在绘制 ggplot 对象的正常过程中完成的。)

黑客

在控制台中运行以下行:

trace(ggplot2:::ggplot_gtable.ggplot_built, edit = TRUE)
Run Code Online (Sandbox Code Playgroud)

应出现一个弹出窗口,显示跟踪函数的实际代码:

function (data) 
{
  plot <- data$plot
    ...
    plot_table$grobs <- plot_table$grobs[c(nrow(plot_table$layout), 
      1:(nrow(plot_table$layout) - 1))]
  }
  plot_table
}
Run Code Online (Sandbox Code Playgroud)

在 之前插入plot_table$layout[which(plot_table$layout$name == "caption"), "r"] <- dim(plot_table)[2]新行plot_table,接近末尾:

function (data) 
{
  plot <- data$plot
    ...
    plot_table$grobs <- plot_table$grobs[c(nrow(plot_table$layout), 
      1:(nrow(plot_table$layout) - 1))]
  }
  plot_table$layout[which(plot_table$layout$name == "caption"), "r"] <- dim(plot_table)[2] # new
  plot_table
}
Run Code Online (Sandbox Code Playgroud)

对于此 R 会话的剩余部分,您绘制的任何 ggplot 中的任何标题都将一直对齐到绘图背景区域的右侧,而不是绘图面板。(此效果不会在新会话中持续存在;如果需要,请重复上述步骤。)

逆转黑客攻击

如果您希望在当前 R 会话中停止该效果,请在控制台中运行以下行:

untrace(ggplot2:::ggplot_gtable.ggplot_built)
Run Code Online (Sandbox Code Playgroud)

现在,任何 ggplot 中的任何标题都将再次与绘图面板右对齐。