2016-11-21 112 views
9

我想創建一個情節標題手動格式上兩行包括2斜體字,我已經做了一些searching 對堆棧Exchange,但還沒有找到了一個很好的解決方案,看似簡單的問題。多行標題與多個斜體字

這兩個物種的科學名稱相當長,因此需要多行標題(ggplot2不會格式化)。

目的:

..........第一行標題與

第二行字anotherItalicSpecies

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"))) 

其中產生以下損壞標題:

enter image description here

回答

10

使用italicatop組合,pastescriptstyle

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")))) 

給你所期望的結果:

enter image description here

使用scriptstyle不是必須的,但恕我直言,讓你的字幕更小更好字體比主標題。

另請參閱?plotmath瞭解其他有用的自定義。

5

作爲在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 

enter image description here


如果你想字體大小是相同的兩條線,設置theme所需size

p + theme(plot.title = element_text(size = 12), 
      plot.subtitle = element_text(size = 12)) 

請注意,標題和副標題在ggplot2 2.2.0中默認爲左對齊。文本可以通過在上面添加hjust = 0.5element_text來居中。

+0

不錯,我只是想從發展版本中包括這些改進在我的答案;-) – Jaap

+0

哈哈:-)(加上加上)。無論如何,顯然ggplot上週更新了,沒有注意到: - /。很好有兩個選擇。 – Jaap

+0

已升級,很好的解決方案!但現在我收到geom_ribbon中y-aesthetic的錯誤...似乎與ggplot 2.2.0相關。我會做一些搜索,但你有什麼想法嗎? – Arch