Ali
Ali

Reputation: 9830

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?

Upvotes: 4

Views: 4961

Answers (2)

ZDinges
ZDinges

Reputation: 53

there is a package, scatterpie, that does exactly what you want to do!

library(ggplot2)
library(scatterpie)

ggplot() + 
  geom_scatterpie(aes(x=X, y=Y, r=0.1), data=foo.m, cols=c("A", "B", "C"))

In the aesthetics, r is the radius of the pie, you can adjust as necessary. It is dependent on the scale of the graph - since your graph goes from 0.0 to 1.0, a radius of 1 would take up the entire graph (if centered at 0.5, 0.5).

Do note that while you will get a legend for the pie slice colors, it will not (to my knowledge) label the slices themselves on the pies.

Upvotes: 2

aosmith
aosmith

Reputation: 36076

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.

Upvotes: 7

Related Questions