2

Simple enough question that seems to be taking a lot of time to solve. When creating a dendrogram using ggraph, I'm trying to include a subscript in the node labels. However, I can't seem to get it to work using expression. For example, if I create some data and a dendrogram like the one below:

library(tidygraph)
library(ggraph)
library(dplyr)

# create some data
nodes <- tibble(
  var = c("x4 ≤ 100", "x1 ≤ 50", "µ", "µ", "µ") 
)

edges <- tibble(
  from = c(1,2,2,1),
  to   = c(2,3,4,5)
)

# turn in tidygraph object
tg <- tbl_graph(nodes = nodes, edges = edges)

# plot using ggraph
ggraph(tg, "dendrogram") +
  geom_edge_elbow() +
  geom_node_label(aes(label = var)) +
  theme_graph() +
  theme(legend.position = "none")

example dendrogram

In the terminal nodes I'm trying to add a subscript to the µ values. Something like: µ1, µ2, etc. But I cant seem to get it to work.

Any suggestions as to how I could solve this?

Electrino
  • 2,636
  • 3
  • 18
  • 40
  • I would normally say that I would use Unicode, see [this SO answer](https://stackoverflow.com/a/27741196/1734247) and [this Wikipedia page](https://en.wikipedia.org/wiki/List_of_Unicode_characters#Superscripts_and_Subscripts), but that doesn't seem to work in this case (at least not on my Windows pc) - probably a ggraph issue? – Dag Hjermann Apr 05 '22 at 09:15

1 Answers1

1

This might not be the most elegant way, but you can use parse = TRUE in geom_node_label; for some reason it keeps expression(), but you can get rid of that afterwards:

library(tidygraph)
library(ggraph)
library(dplyr)

# create some data
nodes <- tibble(
  var = c('"x4 ≤ 100"', '"x1 ≤ 50"', expression("µ"[1]), expression("µ"[2]), expression("µ"[3]))
)

edges <- tibble(
  from = c(1,2,2,1),
  to   = c(2,3,4,5)
)

# turn in tidygraph object
tg <- tbl_graph(nodes = nodes, edges = edges)

# plot using ggraph
ggraph(tg, "dendrogram") +
  geom_edge_elbow() +
  geom_node_label(aes(label = gsub("(expression\\()(.*)(\\))", "\\2", var)), parse=T) +
  theme_graph() +
  theme(legend.position = "none")

Created on 2022-04-05 by the reprex package (v2.0.1)

user12728748
  • 8,106
  • 2
  • 9
  • 14