Reputation: 99
For the data frame below, how can I display labels outside the circle with arrows pointing at them?
asd <- data.frame(a=c("fs","dfg","gf"), b=c(3,5,6))
ggplot(asd, aes(x="", y= b, fill = factor(a))) +
geom_bar(stat = "identity", width =1) +
coord_polar(theta = "y") + theme_void() +
geom_text(aes(label=paste(a, sep = " ", b, "%"), x= 1.3, angle = 0))
Upvotes: 0
Views: 1153
Reputation: 7818
Try with this:
library(ggplot2)
library(dplyr)
asd <- data.frame(a = c("fs","dfg","gf"),
b = c(3,10,5)) # changed to show that order doesnt matter
asd %>%
mutate(prop = b/sum(b)) %>%
arrange(desc(a)) %>%
mutate(lab.ypos = cumsum(prop) - 0.5*prop) %>%
ggplot(aes(x = "", y = prop, fill = a)) +
geom_bar(width = 1, stat = "identity", color = "white") +
coord_polar("y", start = 0, clip = "off")+
geom_segment(aes(x = 1, y = lab.ypos, xend = 2, yend = lab.ypos, colour = a),
size = 1) +
geom_label(aes(y = lab.ypos, label = paste(a, scales::percent(prop))),
x = 2,
size = 5,
color = "white") +
theme_void() +
theme(legend.position = "none")
For the record: don't use pie chart.
There is a reason why doing a pie chart is complicated: you are not supposed to use them. Bar charts are always better.
Upvotes: 2