在饼图上显示百分比值

Display percentage values on a pie chart

我正在尝试使用 ggplot2 绘制饼图。我的代码如下所示。

df <- data.frame(
  variable = c("australia","hungary","germany","france","canada"),
  value = c(632,20,491,991,20)
)
ggplot(df, aes(x = "", y = value, fill = variable)) +
  geom_bar(width = 1, stat = "identity") +
  scale_fill_manual(values = c("red", "yellow","blue", "green", "cyan")) +
  coord_polar(theta = "y") +
  labs(title = "pie chart")

我想显示百分比值。我怎样才能做到这一点?

尝试

df <- data.frame(
  variable = c("australia","hungary","germany","france","canada"),
  value = c(632,20,491,991,20)
)
library(ggplot2)
ggplot(transform(transform(df, value=value/sum(value)), labPos=cumsum(value)-value/2), 
       aes(x="", y = value, fill = variable)) +
  geom_bar(width = 1, stat = "identity") +
  scale_fill_manual(values = c("red", "yellow","blue", "green", "cyan")) +
  coord_polar(theta = "y") +
  labs(title = "pie chart") + 
  geom_text(aes(y=labPos, label=scales::percent(value)))