How to place the labels further away from pie chart in R?
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pct <- round(slices/sum(slices)*100)
lbls <- paste(lbls, pct) # add percents to labels
lbls <- paste(lbls,"%",sep="") # ad % to labels
pie(slices,labels = lbls, col=rainbow(length(lbls)), radius=.2)
You can modify the pie
-function line 50-54
and save it as a new function pie2
Type
pie
Change line 50-54
to
if (!is.na(lab) && nzchar(lab)) {
lines(c(1, 1.35) * P$x, c(1, 1.35) * P$y)
text(1.5 * P$x, 1.5 * P$y, labels[i], xpd = TRUE,
adj = ifelse(P$x < 0, 1, 0), ...)
}
Change line length (default = 1.05
)
lines(c(1, 1.35) * P$x, c(1, 1.35) * P$y)
Change the factor (default = 1.1
)
text(1.5 * P$x, 1.5 * P$y, labels[i], xpd = TRUE,
adj = ifelse(P$x < 0, 1, 0), ...)
Now define pie2
and run the new function
pie2(slices,labels = lbls, col=rainbow(length(lbls)), radius=.2)
You could manually place text with text() and create no labels by rep("",times).
But I agree, pie-charts are a bad way to visualize data.
To provide some code,
pie(slices,labels = rep("",5), col=rainbow(length(lbls)), radius=.8,lty=4)
text(0.9,0.6,"UK")
lines(c(0.6,0.85),c(0.45,0.55))
and align everything where you want it.
If you just want to create one single pie chart this is an option, but getting all those coordinates right can be very frustrating..
Sorry I would have commented rather then answered if I had the option.
You can use ggplot
to form the pie-chart. This will get the labels separate from the pie-chart as a legend.
# R version 3.2.2
install.packages("ggplot2")
library("ggplot2")
slices <- c(10, 12, 4, 16, 8)
lbls <- c("US", "UK", "Australia", "Germany", "France")
pct <- round(slices/sum(slices)*100)
lbls <- paste(lbls, pct) # add percents to labels
lbls <- paste(lbls,"%",sep="") # ad % to labels
df = data.frame(slices = slices,labels = lbls)
ggplot(df,aes(x = factor(1),fill = labels))+
geom_bar(width = 1)+
coord_polar(theta = "y")+
theme(axis.title = element_blank())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.