Search code examples
rggplot2treemap

Image collage treemap look a like


I need to import multiple images and present an output like a collage. I was thinking is doing a treemap with the image size mapped to the score of the character.

df <- data.frame(character=c("Homer","Marge", "Bart", "Lisa","Maggie", "Moe", "Blinky","Bumblebee Man","Duffman","Maude Flanders","Ned Flanders","Rod Flanders","Todd",Jimbo","Otto Mann","Snowball"),score=c(268,267,495, 432, 219, 373, 152, 356, 461, 116,107,165, 305,228, 461, 608))

I had used treemap before and also ggplot geom_tile but i am not sure if it is possible to generate pictures whithin tiles. I don't even know how to insert the images into my dataframe for plotting...

enter image description here


Solution

  • Not really an answer, but a quick demonstration how you start to accomplish your task.

        library(treemap)
        library(gridSVG)
        library(XML)
    
        df <- data.frame(
            character=c("Homer","Marge", "Bart", "Lisa","Maggie", "Moe", "Blinky","Bumblebee Man","Duffman","Maude Flanders","Ned Flanders","Rod Flanders","Todd","Jimbo","Otto Mann","Snowball")
            ,score=c(268,267,495, 432, 219, 373, 152, 356, 461, 116,107,165, 305,228, 461, 608)
        )
    
        tm <- treemap( df, index = "character", vSize = "score" )
    
        svg <- grid.export()$svg
    
        # see http://stackoverflow.com/questions/10688516/fill-svg-path-with-a-background-image-without-knowing-heightwidth?rq=1
        pattern <- newXMLNode(
            "defs"
            ,.children = list(
                newXMLNode(
                    "pattern"
                    , attrs = c(
                        id = "img_homer"
                        ,patternUnits="userSpaceOnUse"
                        ,patternTransform="translate(0, 0) scale(1, -1) rotate(0)"
                        ,width="106"
                        ,height="98"
                    )
                    , .children = newXMLNode(
                        "image"
                        , attrs = c(
                            "xlink:href" = "http://i.imgur.com/JP4s21O.jpg"
                            ,width = 106
                            ,height = 80
                        )
                    )
                )
            )
        )
    
        addChildren( svg, pattern )
    
        homer <- getNodeSet(
            getNodeSet( svg, "//*[contains(@id,'data.2')]")[[1]]
            ,"//*[local-name()='rect']"
        )[[5]]
    
        homer_attrs <- xmlAttrs(homer)
        homer_attrs[["fill"]] <- "url(#img_homer)"
        xmlAttrs(homer) <- homer_attrs
    
        library(htmltools)
        browsable(HTML(saveXML(svg)))