Is there a way (using ggplot or some other package maybe) to angle the labels of a pie chart in R? For example, this code (using R defaults):
data <- c(4,9,2,5)
names <- c("alpha","beta","gamma","delta")
pie(data,names)
Creates this pie chart:
What I want is a pie chart like this (which I created very roughly in PhotoShop):
2
Answers
Just add before calling the
pie
:This will rotate any text in the plot.
Or better :
give different rotations angles:
If you want to set many rotation angles, you need to hack the
pie
function:srt
argumentReplace the line :
by
Now you call the new function :
As @agstudy pointed out, you need to modify the body of the function to create your own
pie
function. Indeed,pie
does not return any value so you don’t know where exactly to put your labels and with which angle.First, you can get the body of
pie
withgraphics::pie
At the end of the function, the pie is drawn with :
The part that is interesting to you is what follows
text
, where you can specify an angle to rotate them (like @agstudy did). In order to use the correct angle, you’ve got to compute it (this is the part where my answer becomes different from the other one…).Actually, it is already computed right before the drawing, with:
you just need to make this function also output the angle:
Then, you can specify the parameter
srt
in thetext
call, putting the angle in degrees, with 2 options according to x:With your data, calling the modified
pie
function, you’ll get the below plot: