0

I wish to create a geom_tile plot which summarises the output of a particular model I've been working with. Specifically, in each tile I want to display the beta coefficient with the p-value on a new line. However I would like to use an italicised 'p' i.e ., p = 0.05

below is what I am trying to achieve except I would like to use italicised 'p'

df = data.frame(x = letters[1:10],y = letters[11:20], value = c(1:10),p = c((1:10)/10))


ggplot(df, aes(x = x, y = y)) +
  geom_tile() +
  geom_text(mapping = aes(label = paste(value, "\n",'p', "=", p)), parse = F, color = "white")

enter image description here

However, when I set parse = T and use expression(), I run into problems

I've tried

ggplot(df, aes(x = x, y = y)) +
  geom_tile() +
  geom_text(mapping = aes(label = paste(value,"/n",expression(italic("p")), "==", p)), parse = T, color = "white")

This only outputs the 'value', not the'p = ..' on the new line

and if I try without usign the new line,

ggplot(df, aes(x = x, y = y)) +
  geom_tile() +
  geom_text(mapping = aes(label = paste(value,expression(italic("p")), "==", p)), parse = T, color = "white")

I get the following error:

Error in geom_text(): ! Problem while converting geom to grob. ℹ Error occurred in the 2nd layer. Caused by error in parse(): ! :1:3: unexpected symbol 1: 1 italic ^

Is there a workaround?

stefan
  • 90,330
  • 6
  • 25
  • 51
L.D.
  • 51
  • 3

1 Answers1

1

If using another package is fine for you then ggtext::geom_richtext makes it easy to achieve your desired result as it allows to style text or single words via HTML, CSS or markdown. To this end wrap the text you want to italicize in * (markdown syntax for italic) and use the html tag <br> to add a new line. Additionally, as geom_richtext resembles geom_label we have to set the fill color as well as the the label box outline color aka label.color to NA:

df <- data.frame(x = letters[1:10], y = letters[11:20], value = c(1:10), p = c((1:10) / 10))

library(ggplot2)
library(ggtext)

ggplot(df, aes(x = x, y = y)) +
  geom_tile() +
  ggtext::geom_richtext(
    aes(label = paste(value, "<br>", "*p*", "=", p)),
    color = "white",
    fill = NA,
    label.color = NA
  )

stefan
  • 90,330
  • 6
  • 25
  • 51