饼图内部显示标签,饼图外部显示百分比

Pie chart with label shown inside and percentage shown outside the pie

我有这样的数据,需要绘制饼图:

# Creat bar chart for jam language
library("ggplot2")  # Data visualization
library("dplyr")    # Data manipulation
library("RColorBrewer")
myPalette <- brewer.pal(5, "Set2") 


all_languages <- data.frame(
  Languages = c("English", "French", "Spanish", "Portuguese", "Others"),
  n = c(81, 4, 3, 2, 3),
  prop = c(87.1, 4.3, 3.2, 2.2, 3.2)
)

# Add label position
all_languages  <-all_languages %>%
  arrange(desc(Languages)) %>%
  mutate(lab.ypos = cumsum(n) - 0.5*n)


ggplot(all_languages , aes(x = "", y = n, fill = Languages)) +
  geom_bar(width = 1, stat = "identity", color = "white") +
  coord_polar("y", start = 0)+
  geom_text(aes(y = lab.ypos, label = n), color = "white")+
  scale_fill_manual(values = myPalette) +
  theme_void()

这是我的图表:

现在我还想在相应的切片处添加图表外的百分比。所以我的英语幻灯片将在圆周外有 87.1%。我的百分比存储在 all_languages$prop 中。我该怎么做?

其次,如何将标签移离中心一点点?这是因为在较小的切片中,数字标签太杂乱了。

ATTEMPT:我确实尝试遵循这个答案

但它抛出一个错误,指出缺少 2 行...特别是,我的西班牙语和葡萄牙语切片没有标签。另外,我的情况不同,因为我想要内部标签和外部百分比。

我尝试使用以下代码来遵循该答案:

all_languages <-all_languages %>%
  arrange(desc(Languages)) %>%
  mutate(end = 2 * pi * cumsum(prop)/sum(prop),
       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))

ggplot(all_languages) + 
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
                   start = start, end = end, fill = Languages)) +
  geom_text(aes(x = 1.05 * sin(middle), y = 1.05 * cos(middle), label = prop,
                hjust = hjust, vjust = vjust)) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1.5, 1.4),  # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1),      # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL)

我收到以下警告

Warning message: Removed 2 rows containing missing values (geom_text)

我的馅饼缺少 2 片的标签:

最终决定:我将遵循 Bappa Das 下面的回答,并稍微编辑一下标签。我会把计数和百分比都放在饼图之外。

您可以将以下代码与基数 R 结合使用

library(RColorBrewer)
Languages = c("English", "French", "Spanish", "Portuguese", "Others")
n = c(81, 4, 3, 2, 3)
prop = c("87.1", "4.3", "3.2", "2.2", "3.2")

lbls <- paste(prop,"%",sep=" ")
lgd <- c("English", "French", "Spanish", "Portuguese", "Others")
cols = brewer.pal(n = length(prop), name = 'Set3')
pie(n, labels = lbls, col=cols)
legend("topright", legend=lgd, cex=0.9, bty = "n", fill = cols)

这是你想要的吗?