ggplot2

时间:2018-01-29 06:56:55

标签: r plot ggplot2

我无法为我的ggplot2图制作副标题。我尝试了答案here,但只有你有一个科学名称才适用。在我的情况下,我有两个科学名称,我想包括在情节标题中。

这是我要包含的副标题:

"大量的金枪鱼(Auxis rochei)和海盗凤尾鱼(Encrasicholina punctifer)归因于2016年上岸量的增加。"

我希望它是多行的,因为它很长。

我的初始代码(一行):

mysubtitle <- expression(paste("High quantity of Bullet tuna ", italic("Auxis rochei"), " and ", "Buccaneer anchovy ", italic("Encrasicholina punctifer"), " were attributed to the increase in the landings in 2016."))

我试过了:

mysubtitle <- expression(atop(paste("High quantity of Bullet tuna (", italic("Auxis rochei"), ") and ", "Buccaneer anchovy (", italic("Encrasicholina punctifer"), ")"), paste("were attributed to the increase in the landings in 2016.")))

上面的代码生成了一个两行标题,但它在我的ggplot2主题plot.subtitle = element_text(hjust = 0)中居中。我希望它与主图标题保持对齐。

注意:我在主图标题中没有问题(在ggplot2 title函数中称为labs)。只在subtitle。另外,我有一个单独的主标题。

1 个答案:

答案 0 :(得分:0)

从“它很愚蠢但它有效”,您可以在第二行的右侧添加持有者字符串以强制左对齐。权利持有人字符串可以是长度为nchar(first_line - nchar(second_line))

的任意字符
library(ggplot2)
first_line<- "High quantity of Bullet tuna (Auxis rochei) and Buccaneer anchovy (Encrasicholina punctifer)"
second_line <- "were attributed to the increase in the landings in 2016."
# the length of holder_string
holder_length <- nchar(first_line) - nchar(second_line)
# generate a arbitrary string with length `holder_length`
holder_string <- stringi::stri_rand_strings(1, holder_length)
# the default font family of ggplot is `sans`, we should set the font family as `mono` (monospaced font) to ensure strings between two lines aligned. 
p  <- ggplot(mtcars, aes(wt, mpg))+ geom_point()
p + labs(subtitle = bquote(atop(
  paste("High quantity of Bullet tuna (", 
    italic("Auxis rochei"), ") and ", "Buccaneer anchovy (", 
    italic("Encrasicholina punctifer"), ")"), 
  paste("were attributed to the increase in the landings in 2016.", 
    phantom(.(holder_string))
  )))
) +
theme(plot.subtitle = element_text(family = "mono"))

<强>编辑

或者,您可以使用substitute()

p + labs(subtitle = substitute(atop(
  paste("High quantity of Bullet tuna (", 
    italic("Auxis rochei"), ") and ", "Buccaneer anchovy (", 
    italic("Encrasicholina punctifer"), ")"), 
  paste("were attributed to the increase in the landings in 2016.", 
    phantom(A))
  ),list(A = holder_string))) + 
theme(plot.subtitle = element_text(family = "mono"))

希望这有帮助!