放置标签而不会浪费实际图表的空间

时间:2019-01-15 22:19:00

标签: r ggplot2

我想显示一个相对较长的标签,并且不希望该标签占用图表的空间。

示例:

library(ggplot2)
out <- ggplot(economics, aes(x=date,y=unemploy)) + 
              geom_line() + 
              labs(title="US unemployment rate", 
                   subtitle="(%)",
                   caption="Source: St. Louis Fed.\n Last observation: April 2014.",
                   tag="us_unempl.pdf (last update: 2019-01-15, 22:30)") +
              theme(plot.caption=element_text(hjust=0),
                    plot.tag=element_text(size=rel(1)),
                    plot.tag.position="bottomright")
print(out)

在此示例中,相对较大的标记会导致实际图表的空间大量损失,因为图表的右边界向左移动。

如何在图表下方显示标签-理想情况下是在标题第二行的对面,还是与标题下方图的右边缘对齐?

注意:我需要其他信息的标题(例如在我的示例中),否则在plot.caption中使用hjust = 1显然是一种自然的解决方案。

1 个答案:

答案 0 :(得分:1)

您可以使用带有x和y位置(plot.tag.position)的数字矢量手动指定标签位置。 c(x, y)应该介于0到1之间。c(0, 0)会将标签置于“左下方”,c(1, 1)会将标签置于“右上方”。

library(ggplot2)
ggplot(mtcars, aes(cyl, mpg)) + 
    geom_line() + 
    labs(title = "US unemployment rate", 
         subtitle = "(%)",
         caption = "Source: St. Louis Fed.\n Last observation: April 2014.",
         tag = "us_unempl.pdf (last update: 2019-01-15, 22:30)") +
    theme(plot.caption = element_text(hjust = 0),
          plot.tag = element_text(size = rel(1)),
          plot.tag.position = c(0.85, 0.05))

enter image description here

相关问题