2017-11-11 374 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