1

There are different discussions on how to use different fonts in the title of ggplot like here - Multi-line ggplot Title With Different Font Size, Face, etc

I am looking for some way to have different lines and fonts on the axis title as well. For example, please consider below ggplot -

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()

In the x-axis title I want to have below statements

1st line -> This is the axis of (font size 11)

2nd line -> wt (font size 12)

Similarly for the y-axis tile.

Is there any way to achieve this?

Any pointer will be very helpful

Brian Smith
  • 1,200
  • 4
  • 16

2 Answers2

1

One option would be the ggtext package which via the theme element element_markdown allows to style theme elements via markdown, HTML and CSS.

To achieve your desired result you have to wrap the parts of your text for which you want to have different font sizes in a <span> tag for which you could set the desired font-size via the style attribute. Also note, that as we are in the World of HTML we have to use a <br> tag for a line break.

Also keep in mind that not all possibilities of CSS are available. According to the docs only

The CSS properties color, font-size, and font-family are currently supported.

library(ggplot2)
library(ggtext)

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point() +
  labs(
    x = paste0("<span style='font-size: 11pt'>This is the axis of</span><br><span style='font-size: 12pt'>wt</span>"),
    y = paste0("<span style='font-size: 11pt'>This is the axis of</span><br><span style='font-size: 12pt'>mpg</span>")) +
  theme(axis.title.x = ggtext::element_markdown(),
        axis.title.y = ggtext::element_markdown())

stefan
  • 90,330
  • 6
  • 25
  • 51
0

While @stefans answer is perfect. I tried to apply what I learned here ggplot2 two-line label with expression using draw_label from cowplot package to this use case:


library(cowplot)  
library(ggplot2)


# define your axis titles
line_1 <- "This is the axis of"
x_line_2 <- "wt"
y_line_2 <- "mpg"

# plot and prepare plot for annotations
p <- ggplot(mtcars, aes(wt, mpg))+
  geom_point() +
  xlab("") +
  ylab("") +
  theme(axis.title.x = element_text(margin = margin(t = 10, r = 0, b = 0, l = 0,
                                                    unit = "mm")),
        axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0,
                                                    unit = "mm"))
        )

# use draw_label with custom positions
ggdraw(p) +
  draw_label(line_1, x = 0.55, y = 0.035, size= 11) + # use relative coordinates for positioning
  draw_label(x_line_2, x = 0.55, y = 0.015, size= 12)+
  draw_label(line_1, y = 0.55, x = 0.028, size= 11, angle = 90) +
  draw_label(y_line_2, y = 0.55, x = 0.038, size= 12, angle = 90)

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66