0

I am creating the following graph with labels being created for each variable as per the below. I can include \n and move the text below the as per the example below, but how can I make the text "Cat.1 [1-3] & Cat.2 [3-5]" smaller? I tried \small but didn't work.

graph <- within(results, Variable_label[Variable=="Var_1"] <- "Average age of individuals \n Cat.1 [1-3] & Cat.2 [3-5]")

graph %>% 
  ggplot(aes(year, Variable_label, fill = other_variable)) +
  geom_tile(color = "white") +
  coord_equal()

I currently have:

enter image description here

shadowspawn
  • 3,039
  • 22
  • 26

1 Answers1

2

It is somewhat hard to put format with line breaks in ggplots.

This is an example made with iris (please share some data so we can reproduce your plot). The key is that expressions in r are parsed by plotmath (see ?plotmath). Here i use the function atop (which is a plotmath function not a real function) to put the text in two lines, and scriptsyle to change size.

Other way is using annotate annotations.

library(ggplot2)
data(iris)

ggplot(iris, aes(Sepal.Width, Species, color = Sepal.Length)) + geom_tile() + 
  scale_y_discrete(labels = \(x) lapply(x, \(x) bquote(atop(.(x),  scriptstyle("your_text_here")))))

Ric
  • 5,362
  • 1
  • 10
  • 23
  • Thanks Ric Villalba, I want to personalise the label for each variable. In your example, each "Species" gets "your_text_here" but I would like the text to be different, so I create the labels first as per my code. I just thought similar to \n, there was a syntax to use there for smaller text, like \small – Daniela Rodrigues Mar 03 '23 at 18:48
  • 1
    \small is latex. \n is newline character escape (latex line breaks are \\, \newline, \break, etc). This is just an example. To personalize "your_text_here" you can create a function taking the label, x, and returning the desired text , or create a list `m <-list(var_1 = c("average age of individuals", "Cat.1 [1-3] & Cat.2 [3-5"), var_2 = c(.....` then subset inside the labeling function : `\(x) lapply(x, \(x) bquote(atop(m[[x]][1], scriptstyle(m[[x]][2]))))` – Ric Mar 04 '23 at 21:06