2

I want to plot a proper pie chart. However, most of the previous questions on this site were drawn from stat = identity. How can I plot a normal pie chart like graph 2 with the angle proportional to proportion of cut? I am using the diamonds data frame from ggplot2.

ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) + 
    geom_bar(width = 1) + coord_polar(theta = "x")

Graph 1 enter image description here

ggplot(data = diamonds, mapping = aes(x = cut, y=..prop.., fill = cut)) + 
    geom_bar(width = 1) + coord_polar(theta = "x")

Graph 2 enter image description here

ggplot(data = diamonds, mapping = aes(x = cut, fill = cut)) + 
    geom_bar()

Graph 3 enter image description here

JetLag
  • 296
  • 1
  • 4
  • 16

3 Answers3

7

We can first calculate the percentage of each cut group. I used the dplyr package for this task.

library(ggplot2)
library(dplyr)

# Calculate the percentage of each group
diamonds_summary <- diamonds %>%
  group_by(cut) %>%
  summarise(Percent = n()/nrow(.) * 100)

After that, we can plot the pie chart. scale_y_continuous(breaks = round(cumsum(rev(diamonds_summary$Percent)), 1)) is to set the axis label based on cumulative percentage.

ggplot(data = diamonds_summary, mapping = aes(x = "", y = Percent, fill = cut)) + 
  geom_bar(width = 1, stat = "identity") + 
  scale_y_continuous(breaks = round(cumsum(rev(diamonds_summary$Percent)), 1)) +
  coord_polar("y", start = 0)

Here is the result.

enter image description here

www
  • 38,575
  • 12
  • 48
  • 84
2

How about this?

ggplot(diamonds, aes(x = "", fill = cut)) + 
  geom_bar() +
  coord_polar(theta = "y")

It yields:

zephryl
  • 14,633
  • 3
  • 11
  • 30
jbtg
  • 21
  • 2
0

I have created ggpie to better create pie, donut and rose pie plot, you can have a try.

This is Vignette.

This is circle label and out of pie:

ggpie(data = diamonds, group_key = "cut", count_type = "full",
      label_info = "all", label_type = "circle",
      label_size = 4, label_pos = "out")

enter image description here

showteth
  • 340
  • 3
  • 10