简体   繁体   中英

Drawing arrows in pie chart with ggplot2

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))

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM