3

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"))
TarJae
  • 72,363
  • 6
  • 19
  • 66
887
  • 599
  • 3
  • 15

1 Answers1

3

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

Eric
  • 2,699
  • 5
  • 17
  • Perfect! Thank you so much! – 887 Mar 12 '21 at 03:43
  • Eric, one question (it's going to be a little difficult to explain). I tried your solution last night and it worked beautifully, however I have replicated it a few times with data, and sometimes when I save the final image (with the annotation for a title) using image_write, R saves two files into my working directory. One is the png file of the tree (with no title), and the other is a TextEdit file (with the title included). Do you have any idea why this might be? I can't seem to figure out any particular rhyme or reason as to when it happens. Thanks! – 887 Mar 12 '21 at 23:09
  • That's a good question @rogues77. Unfortunately, I am not sure about why that happens. Good luck in finding an answer! – Eric Mar 13 '21 at 20:09
  • no worries at all! Fortunately, for the purposes that I'm using them for, the TextEdit files are working, so it's all good! – 887 Mar 15 '21 at 01:11