How to add title to and save vtree object?

214 views Asked by At

I am using the vtree package (which is an awesome tool), and I am struggling to figure out how to add titles to it. Here is a sample tree:

enter image description here

I would like to add a title at the top, but since this isn't a gg object I'm a little lost (I think it's an html object? There isn't too much info out there about the vtree package.). How might I add a title that says "My Tree" at the top? Further, how can I save the image? I have tried using png(), but it will not save. Thanks!

MRE:

structure(list(Var1 = c("A", "B", "C", "D", "A", "A", "B", "C"
), Var2 = c(1L, 2L, 3L, 3L, 1L, 2L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-8L))
vtree(ex, c("Var1", "Var2"))
1

There are 1 answers

4
Eric On BEST ANSWER

Here you go:

ex <- structure(list(Var1 = c("A", "B", "C", "D", "A", "A", "B", "C"
), Var2 = c(1L, 2L, 3L, 3L, 1L, 2L, 1L, 2L)), class = "data.frame", row.names = c(NA, 
-8L))

library(vtree)

foo <- vtree(ex, c("Var1", "Var2"))

# Here is how you would save vtree to PNG
grVizToPNG(foo, width=800)

# Here is how you would annotate the image to include a title

library(magick)

MyimagePNG <- image_read("foo.png")

#Check the image_annotate documentation for information on how to change the text, font, size, etc.

image_annotate(MyimagePNG, "My Tree", size = 35, gravity = "northwest")

# Note the other choices for the gravity parameter:
# northwest - Position object at top-left of region.
# north - Position object at top-center of region.
# northeast - Position object at top-right of region

# If you want to save the annotated image:

bar <- image_annotate(MyimagePNG, "My Tree", size = 35, gravity = "north")

image_write(bar, path = "final.png", format = "png")

enter image description here