如何将标题与换行符左对齐?

时间:2018-09-19 01:34:15

标签: r ggplot2

我正在ggplot2中制作一个图表,我想通过左对齐在图表的自由标题中节省空间。问题是,使用@Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } 不能正常工作。

hjust

这将产生一个图表... enter image description here

我希望“此处”和“换行符”与y轴标题对齐。单独使用ggplot2可能吗?

1 个答案:

答案 0 :(得分:2)

您可以将geom_textcoord_cartesian(clip = "off")一起使用,以允许在绘图面板之外绘制绘图元素

library(ggplot2)

ggplot(
  data = cars,
  aes(x = speed,
      y = dist)) +
  geom_point() +
  labs(subtitle = "This subtitle will also have\na linebreak") +
  geom_text(
    x = 1,
    y = 160,
    inherit.aes = FALSE,
    label = "Here is a very long title that will need a\nlinebreak here",
    check_overlap = TRUE,
    hjust = 0,
    size = 6
  ) +
  coord_cartesian(clip = "off") +
  theme(plot.margin = unit(c(4, 1, 1, 1), "lines"))

另一种方法是使用egg软件包中的ggarrange,该软件包具有top参数,可以用于标题

chart <- ggplot(
  data = cars,
  aes(
    x = speed,
    y = dist)) +
  geom_point() +
  labs(subtitle = "This subtitle will also have\na linebreak")


library(grid)
# devtools::install_github('baptiste/egg')
library(egg)
#> Loading required package: gridExtra

ggarrange(chart, 
          ncol = 1,
          top = textGrob(
            "Here is a very long title that will need a\nlinebreak here",
            gp = gpar(fontface = 1, fontsize = 14),
            hjust = 0,
            x = 0.01)
          )

reprex package(v0.2.1.9000)于2018-09-18创建