1

I'm trying to define different margins for x-axis labels in ggplot2 using css syntax, as allowed by ggtext package. I created an object with the CSS selector and used element_markdown() for axis.text.x. However, nothing happens to the plot.

Here is an example:

    library(ggplot2)
    library(ggtext)
    df <- data.frame(x = runif(n = 20, min = 1, max = 10),
                     y = runif(n = 20, min = 1, max = 10))
    num1 <- c(1, 2, 3, 4, 5)
    num2 <- c(6, 7, 8, 9, 10)
    labels <- rep(NA, 10)
    labels[num1] <- paste0("<span style='margin-top:16px'>", num1, "</span>")
    labels[num2] <- paste0("<span style='margin-top:64px'>", num2, "</span>")
    
    ggplot(df, aes(x = x, y = y)) +
      geom_point() +
      scale_x_continuous(name = "",
                         limits = c(0, 10),
                         breaks = seq(1, 10, 1),
                         labels = labels) +
      theme(axis.text.x = ggtext::element_markdown())

Plot 01

We can see that labels didn't change their position. But, when I tried other selector, i.e., font-size, it worked.

Example:

labels[num1] <- paste0("<span style='font-size:12px'>", num1, "</span>")
labels[num2] <- paste0("<span style='font-size:6px'>", num2, "</span>")

    ggplot(df, aes(x = x, y = y)) +
      geom_point() +
      scale_x_continuous(name = "",
                         limits = c(0, 10),
                         breaks = seq(1, 10, 1),
                         labels = labels) +
      theme(axis.text.x = ggtext::element_markdown())

Plot 02

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • 2
    Possible due to [`ggtext` ... implements only an extremely limited subset of Markdown/HTML/CSS](https://github.com/wilkelab/ggtext) – user20650 Jan 16 '22 at 00:27
  • 1
    Only "The CSS properties color, font-size, and font-family are currently supported." See https://wilkelab.org/ggtext/articles/theme_elements.html. – stefan Jan 16 '22 at 00:51
  • 1
    @user20650 and stefan, thanks for the answers! – diegogaldinof Jan 16 '22 at 17:07

0 Answers0