'gridtext::element_markdown doesn't apply margin with css selector

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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source