r - 如何将标签放在饼图之外?

标签 r ggplot2 pie-chart

如何将标签放在饼图之外,以便标签位于正确的位置?

Product <- c("Product1","Product2","Product3","Product4","Product5","Product6","Product7")
Value <- c(1000000,200002,599996,1399994,2199992,2999990,3799988)
df <- data.frame(Product,Value)
df$Label <- paste(Product, paste(round(((df$Value/sum(df$Value))*100),2),"%"), sep="-")

library(ggplot2)

p <-  ggplot(df, aes(x = 1, y = Value, fill = Product)) + geom_bar(stat = "identity")
p <- p + coord_polar(theta = 'y') + theme_void()
p <- p + geom_text(aes(label = Label), position = position_stack(vjust = 0.5))

enter image description here

最佳答案

使用:

library(dplyr)
df <- df %>% 
  mutate(end = 2 * pi * cumsum(Value)/sum(Value),
         start = lag(end, default = 0),
         middle = 0.5 * (start + end),
         hjust = ifelse(middle > pi, 1, 0),
         vjust = ifelse(middle < pi/2 | middle > 3 * pi/2, 0, 1))

library(ggforce) # for 'geom_arc_bar'
ggplot(df) + 
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
                   start = start, end = end, fill = Product)) +
  geom_text(aes(x = 1.05 * sin(middle), y = 1.05 * cos(middle), label = Label,
                hjust = hjust, vjust = vjust)) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1.5, 1.5),  # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1.1),    # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL)

给出:

enter image description here

关于r - 如何将标签放在饼图之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48184645/

相关文章:

r - Boxplot.stats R 未识别异常值

r - 在 R 中将字符串修剪为特定数量的字符

linux - 无法安装 rJava

r - 将自定义图例添加到 ggplot

r - ggrepel:在点上方绘制标签

mysql - SQL 查询需要通过连接更多表在 MySQL 中按 TYPE 和 PERCENTAGE 分组的两列中获得结果

r - 合并逻辑/二进制数据框的相同列名

从图例中删除 ggplot2 的 geom_point 图标

r - R 中的圆环图自定义问题

r - 带标签的多级饼图