饼图中的百分比而不是计数

Percentage inside the pie chart instead of count

我的数据框

dput(d)
structure(list(x = c("Organonitrogen compound metabolic process", 
"Cellular process", "Nitrogen compound metabolic process", "Primary metabolic process", 
"Organic substance biosynthetic process", "Metabolic process", 
"Cellular nitrogen compound biosynthetic process", "Cellular metabolic process", 
"Organic substance metabolic process", "Cellular biosynthetic process"
), freq = c(71, 119, 87, 89, 52, 94, 42, 89, 89, 49)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

我的代码运行生成饼图

d$perc <- round(100 * d$freq / sum(d$freq))

ggplot(data = d, aes(x = 0, y = freq, fill = x)) + 
  geom_bar(stat = "identity") +
  geom_text(aes(label =  perc), position = position_stack(vjust = 0.5)) +
  scale_x_continuous(expand = c(0,0)) +
  labs(fill = 'Type', x = NULL, y = NULL, title = 'Pathway Pie chart', subtitle = 'percentages') +
  coord_polar(theta = "y") +
  theme_minimal()

我得到了这样的东西

但我想看到这样的东西。

如有任何帮助或建议,我们将不胜感激

您可以使用 theme_void 删除坐标轴和刻度,并使用 sprintf 显示百分比符号。

ggplot(data = d, aes(x = 0, y = freq, fill = x)) + 
  geom_bar(stat = "identity") +
  geom_text(aes(label =  sprintf("%d%%",perc)),
            position = position_stack(vjust = 0.5),
            size = 3) +
  scale_x_continuous(expand = c(0,0)) +
  labs(fill = 'Type', x = NULL, y = NULL, title = 'Pathway Pie chart', subtitle = 'percentages') +
  coord_polar(theta = "y") +
  theme_void()

scales::percent()就是为此而设计的。尝试

geom_text(aes(label = scales::percent(freq/sum(freq), 1)),
          position = position_stack(vjust = 0.5)) +

因为你计算出来的百分比是perc,所以可以直接传入percent()。 (注意它的参数 accuracyscale。在你的情况下,它们都应该是 1)

geom_text(aes(label = scales::percent(perc, 1, 1)),
          position = position_stack(vjust = 0.5)) +

您可以搜索 ?scales::percent 以查看更多要调整的参数。