ggplot 2中的多行标题,带有多个斜体字

Arc*_*rch 11 plot r ggplot2

我试图创建一个手动格式化在两行上的情节标题,其中包括两个斜体字,我已经 在Stack Exchange上做了一些搜索但是没有找到一个很好的解决方案来解决这个看似简单的问题.

这两个物种的科学名称相当长,因此需要多行标题(ggplot2不会对此进行格式化).

目的:

..........第一行标题与物种

第二行的话是另一种语言的结尾

ggplot(mtcars,aes(x=wt,y=mpg))+
  geom_point()+
  labs(title= expression(paste(atop("First line of title with ", atop((italic("Species")))),"
       secondline words", italic("anotherSpecies"), "the end")))
Run Code Online (Sandbox Code Playgroud)

产生以下错位标题:

在此输入图像描述

Jaa*_*aap 14

使用的组合atop,paste,italicscriptstyle:

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  labs(title = ~ atop(paste('First line of title with ',italic("Species")),
                      paste(scriptstyle(italic("Species")),
                            scriptstyle(" secondline words "),
                            scriptstyle(italic("anotherSpecies")),
                            scriptstyle(" the end"))))
Run Code Online (Sandbox Code Playgroud)

给你想要的结果:

在此输入图像描述

使用scriptstyle不是必需的,但是使用比主标题更小的字体更好的字幕.

另请参阅?plotmath其他有用的自定义.


Hen*_*rik 7

作为插入换行符的替代方法title,您可以titlesubtitle(可从ggplot 2.2.0)一起使用.可能这使得结构plothmath更加简单明了.

p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  labs(title = expression("First line: "*italic("Honorificabilitudinitatibus")),
       subtitle = expression("Second line: "*italic("Honorificabilitudinitatibus praelongus")*" and more"))
p
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


如果你想字体大小是相同的两条线,设置所需的sizetheme.

p + theme(plot.title = element_text(size = 12),
          plot.subtitle = element_text(size = 12))
Run Code Online (Sandbox Code Playgroud)

请注意,默认情况下,标题和副标题都是左对齐的ggplot2 2.2.0.通过添加hjust = 0.5element_text上面可以使文本居中.

  • @Arch如果您遇到新问题,最好发布一个新问题imo. (2认同)