问题
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