通过表达式生成时如何在ggplot2中对齐标题和副标题

Kon*_*rad 5 charts r ggplot2 boxplot plotmath

我正在使用下面的代码生成一个简单的箱线图ggplot2

# Libs data
data("mtcars"); require(ggplot2); require(ggthemes)
# Chart
ggplot(data = mtcars) +
  geom_boxplot(aes(y = wt, x = as.factor(am)),
               fill = "gray87") +
  xlab("AM") +
  ylab("WT") +
  theme_gdocs() +
  ggtitle("WT by AM") +
  theme(axis.title.y = element_text(angle = 90),
        axis.ticks = element_line(colour = "black", linetype = "solid",
                                  size = 0.5),
        panel.grid = element_line(colour = "gray"))
Run Code Online (Sandbox Code Playgroud)

生成的图表相当简单: 第一张图表

任务

我想为我的图表添加一个副标题,并对它的呈现方式进行一些控制。我正在关注此讨论并使用代码:

# Chart
ggplot(data = mtcars) +
  geom_boxplot(aes(y = wt, x = as.factor(am)),
               fill = "gray87") +
  xlab("AM") +
  ylab("WT") +
  theme_gdocs() +
  ggtitle(expression(atop("WT by AM", 
                          atop(italic("Some crucial note that has to be here"), "")))) +
  theme(axis.title.y = element_text(angle = 90),
        axis.ticks = element_line(colour = "black", linetype = "solid",
                                  size = 0.5),
        panel.grid = element_line(colour = "gray"))
Run Code Online (Sandbox Code Playgroud)

我得到以下图表: 第二次尝试


这看起来很糟糕,我想改变一些事情:

  1. 制作副标题标题左对齐
  2. 减少两行之间的空白
  3. 保持字体粗体

尝试

我尝试了不同的东西,例如下面的代码:

ggplot(data = mtcars) +
  geom_boxplot(aes(y = wt, x = as.factor(am)),
               fill = "gray87") +
  xlab("AM") +
  ylab("WT") +
  theme_gdocs() +
  ggtitle(expression(atop("WT by AM", 
                          atop(italic("Stupid note"), "")))) +
  theme(axis.title.y = element_text(angle = 90),
        axis.ticks = element_line(colour = "black", linetype = "solid",
                                  size = 0.5),
        panel.grid = element_line(colour = "gray"),
        plot.title = element_text(size = 16, colour = "black", hjust = -1))
Run Code Online (Sandbox Code Playgroud)

但它完全隐藏了标题:

缺少标题

C8H*_*4O2 3

在“这很愚蠢但它有效”文件中,您可以在中心右侧添加空格以强制左对齐。可以使用数学确定正确的空格数,但我不知道如何将字符串变量传递回atop.

# Chart
ggplot(data = mtcars) +
  geom_boxplot(aes(y = wt, x = as.factor(am)), fill = "gray87") +
  xlab("AM") + ylab("WT") + theme_gdocs() +
  ggtitle(expression(atop("WT by AM                            ", 
                          atop(italic("Some crucial note that has to be here"), "")))) +
  theme(axis.title.y = element_text(angle = 90),
        axis.ticks = element_line(colour = "black", linetype = "solid", size = 0.5),
        panel.grid = element_line(colour = "gray"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述