在ggplot2中绘制饼图

时间:2017-11-11 12:54:48

标签: r plot ggplot2 pie-chart

我想绘制一个合适的饼图。但是,此网站上的大多数先前问题均来自stat = identity。如何绘制正常的饼图,如图2,其角度与cut的比例成正比?我正在使用ggplot2中的diamonds数据框。

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

图1 enter image description here

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

图2 enter image description here

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

图3 enter image description here

2 个答案:

答案 0 :(得分:4)

我们可以先计算每个cut组的百分比。我使用dplyr包来完成这项任务。

library(ggplot2)
library(dplyr)

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

之后,我们可以绘制饼图。 scale_y_continuous(breaks = round(cumsum(rev(diamonds_summary$Percent)), 1))是根据累积百分比设置轴标签。

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)

结果如下。

enter image description here

答案 1 :(得分:1)

怎么样?

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

它产生:

https://imgur.com/a/leSmIPT