I’m making a set of pie charts in R (with a loop) out of subsets from a single data frame. I get nice pie charts but the colors are allocated always in the same order in each pie while I would like to have the colors allocated to the same values, throughout all the pies.
my code is :
for (i in 1:length(voisins)) {
y <- subset(zz, Destination==voisins[i])
pie(y$pc,labels=y$Names, col=terrain.colors(nrow(y)) , main=c(y$country[1]))
I would like to have the same color for each y$Names.
I’m not allowed to put an image here, so I put it there : http://cl.ly/image/080t2Q1v1q3V
It would be easier to read if the same region had the same color ! Is there a way to achieve this ?
Solution :
thank you, Arun, for your answer but unfortunately this doesn’t produce the result I want, probably I didn’t explain it clearly enough. I believe ggplot is a better graphical package and I will learn how to use it soon, but for the moment I don’t have time and your answer anyway put me on the right track. I found a solution : actually if you make a bigger “t” (with more rows) in your example and then take subsets of it resulting in smaller t1, t2, t3, …, with not always the same t$id, so let’s say in t1 we would have id = (2,4,9,3) and in t2 id = (4,6,3), and so on. You will see that the colors are allocated always in the same order, which gives in t1 2=red, 4=green, 9=blue, 3=violet, while in t2 4=red, 6=green and 3=blue. So the colors vary from one pie to another and I want to have always 2=red, 4=green, 3=blue, 9=violet. The solution I found is to merge a color column to t according to t$id, then keep it in the subsets t1, t2, t3, … and set col=t1$color , col=t2$color, and so on in the pie command. It was finally easy but I had hoped for an automatic solution and I will see Paul’s one later. Didier
Let me first state that piecharts are a bad idea to begin with as they have major perceptual problems, see e.g. here.
Then to get back ot the problem, I would use
ggplot, and more specifically facetting. First create one piechart:To make a piechart per level of a variable you can use
facet_wrap, e.g. per unique level of the variablegearinmtcars: