Plotting pie charts in ggplot2

强颜欢笑 提交于 2019-12-21 06:58:01

问题


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

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

Graph 2

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

Graph 3


回答1:


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.




回答2:


How about this?

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

It yields:

https://imgur.com/a/leSmIPT



来源:https://stackoverflow.com/questions/47238098/plotting-pie-charts-in-ggplot2

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