Display percentage values on a pie chart [duplicate]

别等时光非礼了梦想. 提交于 2019-12-10 12:27:26

问题


I am trying to draw a pie chart with ggplot2. My code is shown below.

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

I would like to display percentage values. How can I do that?


回答1:


Try

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


来源:https://stackoverflow.com/questions/35682703/display-percentage-values-on-a-pie-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!