Search code examples
rggraph

How to use subscript with ggraph in R?


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?


Solution

  • 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)