2017-11-11 389 views
0

我想绘制一张适当的饼图。但是,此网站上的大多数以前的问题都是从stat = identity中抽取的。如何绘制一个正常的饼图,如图2所示,角度与cut的比例成正比?我正在使用ggplot2的diamonds数据帧。在ggplot2中绘制饼图

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

回答

3

我们可以先计算出percen每个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

+0

这看起来像很多工作... – JetLag