Home > Blockchain >  How do I add 2 subtitles to plot in ggplot and make one of them bold?
How do I add 2 subtitles to plot in ggplot and make one of them bold?

Time:01-18

may be easy but can't figure it out:

I want to add two subtitles to my plot and make the first bold but I can't find a way to do it without scrambling everything around. I tried this:

ggplot(mtcars, aes(x = wt, y = mpg))  
  geom_point()  
  labs(title = expression(""*bold("Title")),
       subtitle = expression(""*bold("First subtitle")*"\nSecond subtitle"))

But for the second subtitle the \n does not work and stays on the same line. How do I put it below without making it bold? Thanks in advance!

CodePudding user response:

Alternatively, you can use element_markdown from ggtext. There, you need to use <br> to create a line break.

library(ggplot2)
library(ggtext)
ggplot(mtcars, aes(x = wt, y = mpg))  
  geom_point()  
  theme(
    plot.title = element_markdown(),
    plot.subtitle = element_markdown()
  )  
  labs(title = "**Title**",
       subtitle = "**First subtitle**<br>Second subtitle")

Created on 2023-01-17 by the reprex package (v1.0.0)

CodePudding user response:

How about this:

library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg))  
  geom_point()  
  labs(title = expression(bold(Title)),
       subtitle = expression(atop(bold(First~subtitle),~~~~Second~subtitle)))

Created on 2023-01-17 by the reprex package (v2.0.1)

This answer proposed the use of atop() instead of a line break.

  • Related