wwl wwl - 1 month ago 12
R Question

floating.pie in plotrix in R

I'm using R. My ultimate objective is to have a GIS map of Minnesota at the county level, and in each county there'll be a pie chart, representing the proportion of primary, secondary, and tertiary people employed.

I have a dataframe containing employment statistics. Each row is a county, and the columns are employment in the primary, secondary, and tertiary sector. The first ten rows look like this.

[,1] [,2] [,3]
[1,] 0 94 2208
[2,] 0 45568 65678
[3,] 0 3124 6262
[4,] 48 3908 11278
[5,] 0 6949 9779
[6,] 0 283 992
[7,] 0 7797 27130
[8,] 15 4471 6710
[9,] 51 1973 5768
[10,] 44 14188 23040


To put a pie chart, I use
floating.pie
function of
plotrix
package and iterate over all counties. (
mn_county
is my GIS shapefile, but you don't have to bother about that)

floating.pie(coordinates(mn_county)[s, ][1], coordinates(mn_county)[s, ][2], c(pri, sec,tert), radius = rad
, col = c(rgb(255, 0, 0, max = 255, alpha = 125, names = "red50"), rgb(0, 255, 0, max = 255, alpha = 125, names = "green50"), rgb(0, 0, 255, max = 255, alpha = 125, names = "blue50")))


For my pie chart, I want primary employment to be red, secondary employment to be green, and tertiary employment to be blue. The problem is, when primary employment = 0, R shades secondary employment as red and tertiary employment as green. How can I prevent this from happening?

Answer

In principle you could hack the floating.pie function yourself (zeros are excluded because they break some of the internal computations; it should be possible to work around this) or send a request to the package maintainer ...

An easy hack is to add a small value to all of your categories (small enough that you'll never notice the difference visually); alternatively you could just use min(pri,eps) ...

dat <- data.frame(pri=c(0,10,20),
                  sec=c(10,20,30),
                  tert=c(10,10,10))
n <- 3
library(plotrix)
plot(c(0,n+1),c(0,n+1),axes=FALSE,ann=FALSE,type="n")
eps <- 0.001
for (i in 1:n) {
    with(dat[i,],floating.pie(i,i,c(pri+eps,sec+eps,tert+eps),
                              col=c("red","green","blue"),radius=0.5))
}

enter image description here

Other unsolicited advice:

  • red/green/blue aren't the best possible colour representations (primary red/green are indistinguishable to dichromats), you might look at the RColorBrewer package ...
  • you might want to have a look at this answer ...
Comments