wilkox / treemapify

🌳 Draw treemaps in ggplot2
http://wilkox.org/treemapify
213 stars 18 forks source link

How do I use annotate() with treemapify? #33

Closed sinclairtarget closed 5 years ago

sinclairtarget commented 5 years ago

I am trying to directly annotate a treemapify plot using the annotate() function and the "label" geom. I can get the annotation to appear, but I cannot move the annotation away from the very center of the panel area. I have tried setting x, y, hjust, and vjust.

Is there any prior art on how to annotate a treemap?

wilkox commented 5 years ago

From ggplot2's perspective, treemaps don't have x or y scales. So, if you try to add a geom positioned by x and y, ggplot2 will create new x and y scales just for that single geom, which by default will position it in the centre of the plot.

One way around this is to manually set the x and y limits, for example between 0 and 1. Then you can position the annotation wherever you want within that coordinate system.

library(ggplot2)
library(treemapify)

ggplot(G20, aes(area = gdp_mil_usd)) +
  geom_treemap() +
  annotate(geom = "text", x = 0.25, y = 0.25, label = "The annotation") +
  scale_x_continuous(limits = c(0, 1)) +
  scale_y_continuous(limits = c(0, 1))

Created on 2019-02-10 by the reprex package (v0.2.1)

sinclairtarget commented 5 years ago

Thanks so much, @wilkox

brianmsm commented 2 years ago

This works fine if the annotation is to be done inside the plot. How could I handle annotations outside the plot?

wilkox commented 2 years ago

@brianmsm This depends a lot on what annotations you want to add and where you want to place them – can you give more detail on what you are trying to achieve?