Search code examples
rgroupinglinetreemap

How can you change the line type and colour of the values inside a certain subgroup in R with treemapify?


I want to change the dividing lines of the values that are inside a certain subgroup in a treemap in R.

I will use a dataframe that's already been used in another question (different question):

name <- c("France", "Germany", "Chad", "Mali", "France", "Germany", "Chad", "Mali")
population <- c(100, 200, 300, 400, 500, 600, 700, 800)
parent <- c("Europe","Europe","Africa","Africa", "Europe","Europe","Africa","Africa")
period <- c("a", "a", "a", "a", "b", "b", "b", "b")
df <- data.frame(period, name, population, parent)

What I want is to make a treemap, in which the lines that divide the values within the "Europe" subgroup (i.e., the lines of France and Germany) are dashed and white, and the rest should be solid and white (the one dividing the subgroups would also be thicker). This divided by periodo (so a facet_wrap(~period))

I have tried with geom_treemap_subgroup_border(data = subset(df, parent == "Europe"), linetype = "dashed", size = 1.5, color = "white"), but that did not work.

I already did it in Excel, but I want to know if you can do it in R as well. I'll attach a photo of what I mean (but what I still want is to keep the whole area surrounding the treemap to be white, so the outside borders of the blue ones should also be solid and not dashed; the dashed lines should be the ones inside the rectangles). The picture is different because it's different data but it is the same idea: enter image description here

Does anyone know how to do this in R with treemapify? Thanks!


Solution

  • To set the linetypes for the inner borders map parent on the linetype aes inside geom_treemap, then set your desired linetypes via scale_linetype_manual. Then use geom_treemap_subgroup_border to draw an outer border line for the subgroups (which requires to map parent on the subgroup aes).

    Note: You can increase the width of the interior borders by adding e.g. size= to geom_treemap. However, as a result you will get two interior borders, one with the set size and one with a smaller (default?) width. I haven't found an option to avoid that (or a reason why this is the case). Perhaps a bug.

    library(ggplot2)
    library(treemapify)
    
    ggplot(df, aes(
      area = population, fill = parent,
      label = name, subgroup = parent
    )) +
      geom_treemap(
        aes(linetype = parent),
        colour = "blue"
      ) +
      geom_treemap_text(colour = "white", place = "centre") +
      geom_treemap_subgroup_border(
        size = 4,
        color = "red",
        linetype = "solid"
      ) +
      scale_linetype_manual(
        values = c(Europe = "dashed", Africa = "solid")
      ) +
      facet_wrap(~period)
    

    enter image description here