-3

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?

bhl
  • 11
  • 1
  • 2
  • 1
    What did you try? Why did it not work? (Someone has probably already told you, but in case that hasn't happened yet, pie-charts are not the best way to display data. You could consider a barchart) – Heroka Feb 28 '16 at 12:47
  • Earlier today, I pointed to the [first link from above](http://stackoverflow.com/questions/16184188/ggplot-facet-piechart-placing-text-in-the-middle-of-pie-chart-slices). Please study the [first answer](http://stackoverflow.com/a/22804400/2204410) carefully. It gives a detailed explanation on how to do this. – Jaap Feb 28 '16 at 13:00
  • @Heroka My effort has already shown as a code in the question. My code is working properly. But I need to display percentages on the plot. Writing comment without reading a question is not good. – bhl Feb 28 '16 at 13:08
  • 2
    I read your question. There is zero effort in it on how to add percentages. – Heroka Feb 28 '16 at 13:25

1 Answers1

6

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)))
lukeA
  • 53,097
  • 5
  • 97
  • 100
  • Thank you for your answer. Is it possible to remove the x and y axis labels? I also need to increase the font size of the percentage values. – bhl Feb 28 '16 at 13:20
  • 1
    @bhl Please do search for answers before asking additional questions in comments. _All_ your questions have been answered several times on SO. – Henrik Feb 28 '16 at 14:16
  • @bhl #1 You could add `+ theme(axis.title = element_blank())` or `+ labs(x="", y="")` or `+ xlab("")`. #2 To increase size, e.g. use `+ geom_text(aes(y=labPos, label=scales::percent(value)), size=12)`. – lukeA Feb 28 '16 at 15:50
  • @lukeA Thank you very much for your sincere help. – bhl Feb 29 '16 at 02:38