Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting pie charts in ggplot2

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

like image 796
JetLag Avatar asked Feb 14 '26 00:02

JetLag


2 Answers

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

like image 52
www Avatar answered Feb 16 '26 14:02

www


How about this?

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

It yields:

like image 31
jbtg Avatar answered Feb 16 '26 14:02

jbtg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!