HannahTamia
HannahTamia

Reputation: 5

Legend in piechart not appearing correctly

I would like to move my pie chart to the left, because the legend is too close and it is therefore cutting words in my legend (Micro-mammifères), but I don't know how to do that. I also do have the percentages values that are overlapping, and I would like to be able to read them correctly. I tried to increase the radius but it didn't work, and made the legend disappear.

slices <- c(62,6,1,0.5,13,1,0.4,14,0.1,2)
pct <- c(62,6,1,0.5,13,1,0.4,14,0.1,2)
lbls <- paste(pct,"%",sep=" ")
lgd <- c("Elan", "Renne","Castor", "Chevreuil", "Lièvre", "Renard", "Sanglier","Porc", "Mustélidés", "Micromammifères")
cols = brewer.pal(n = length(slices), name = 'Set3')

pie(slices,labels = lbls, col=cols)
legend(1.1,0.6,legend=lgd,cex=0.9, bty = "n", fill = cols)

Upvotes: 0

Views: 1814

Answers (2)

user2554330
user2554330

Reputation: 44788

The main problem with the pie() function is that it always plots the pie in the middle of the plot region. You can make the region rectangular as @dcarlson did to leave room around the edges, but you'll have a big white space on the left.

To avoid that, you can use the layout() function to split the plot region into two pieces, and put the pie in the left piece. For example,

dev.new(width=10, height=6)
layout(matrix(1:2, nrow=1), widths = c(1,0.666))
pie(slices,labels = lbls, col=cols)
plot.new()
legend("center",legend=lgd,cex=0.9, bty = "n", fill = cols)

This gives a plot that still has too much whitespace for my taste, but at least it is balanced:

screenshot

You could try playing with the dimensions to improve the look. You might also want to adjust the margins, e.g. par(mar = c(0,0,0,0)) reduces all the margins to zero.

Upvotes: 0

dcarlson
dcarlson

Reputation: 11046

Pie charts are discouraged in base R (see the manual page ?pie) so they do not include a number of useful options. We can get closer to what you want by reducing the size of the labels, dropping the percent sign, and changing the size of the plot window. I'm just including changed code:

pct <- c("62", "6", "1", ".5", "13", "1", ".4", "14", ".1", "2")
dev.new(width=10, height=8)
pie(slices, labels=pct, col=cols, cex=.75)
title(xlab="Percentage of Total", line=0)
legend("topright", legend=lgd, bty="n", fill=cols)

There are some other implementations of pie charts in plotrix and ggplot that might get you closer to what you want.

Pie Chart

Upvotes: 1

Related Questions