Search code examples
rggplot2pie-chartscatter-plot

tiny pie charts to represent each point in an scatterplot using ggplot2


I want to create a scatter plot, in which each point is a tiny pie chart. For instance consider following data:

foo <- data.frame(X=runif(30), Y=runif(30),A=runif(30),B=runif(30),C=runif(30))

The following code will make a scatter plot, representing X and Y values of each point:

library(reshape2)
library(ggplot2)
foo.m <- melt(foo, id.vars=c("X","Y"))
ggplot(foo.m, aes(X,Y))+geom_point()

enter image description here

And the following code will make a pie chart for each point:

p <- ggplot(foo.m, aes(variable,value,fill=variable)) + geom_bar(stat="identity")
p + coord_polar() + facet_wrap(~X+Y,,ncol=6) + theme_bw()

enter image description here

But I am looking to merge them: creating a scatter plot in which each point is replaced by the pie chart. This way I will be able to show all 5 values (X, Y, A, B, C) of each record in the same chart.

Is there anyway to do it?


Solution

  • This is the sort of thing you can do with package ggsubplot. Unfortunately, according to issue #10 here, this package is not working with R 3.1.1. I ran it successfully if I used an older version of R (3.0.3).

    Using your long dataset, you could put bar plots at each X, Y point like this:

    library(ggplot2)
    library(ggsubplot)
    
    ggplot(foo.m) +
        geom_subplot2d(aes(x = X, y = Y, 
                        subplot = geom_bar(aes(variable, value, fill = variable), stat = "identity")),
                    width = rel(.5), ref = NULL)
    

    enter image description here

    This gives the basic idea, although there are many other options (like controlling where the subplots move to when there is overlap in plot space).

    This answer has more information on the status of ggsubplot with newer R versions.