2017-12-27 1469 views
3

我創建了一個清單,1列的值的計數:從數列與百分比的餅圖創建爲標籤

ataques_tot <- count(t1$attacktype1_txt) 
ataques_tot 
           x freq 
1     Armed Assault 40223 
2     Assassination 18402 
3    Bombing/Explosion 83073 
4 Facility/Infrastructure Attack 9581 
5      Hijacking 11733 
6    Unarmed Assault 913 
7      Unknown 6425 

我想打一個餅圖與百分比,不與計數出來了。我試圖把該列表的DF,然後使用這樣的事情:

ggpie(ataques_tot, "value", label = "group", 
    fill = "group", color = "white") 

但我很努力了很多,也許這個選項已經在實施GGPLOT2 ...

我已經試過也這個:

pie <- ggplot(t1, aes(x = factor(1), fill = factor(attacktype1_txt))) + 
    geom_bar(width = 1) 
pie + coord_polar(theta = "y") 

但它給了我一個計數,而不是分類變量的百分比。之後,我只需要賦予劇情權利,就是這樣。

回答

2

計算百分比:

d$perc <- round(100 * d$freq/sum(d$freq)) 

然後劇情:

ggplot(data = d, aes(x = 0, y = freq, fill = x)) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label = perc), position = position_stack(vjust = 0.5)) + 
    scale_x_continuous(expand = c(0,0)) + 
    labs(fill = 'Type', x = NULL, y = NULL, title = 'Deaths', subtitle = 'in perventages') + 
    coord_polar(theta = "y") + 
    theme_minimal() 

這給:

enter image description here


使用的數據:

d <- structure(list(x = c("Armed Assault", "Assassination", "Bombing/Explosion", "Facility/Infrastructure Attack", "Hijacking", "Unarmed Assault", "Unknown"), 
        freq = c(40223L, 18402L, 83073L, 9581L, 11733L, 913L, 6425L)), 
       .Names = c("x", "freq"), class = "data.frame", row.names = c(NA, -7L)) 
+0

謝謝,差不多了。我如何刪除中心上的白色五邊形,並命名軸和圖例? –

+0

@ Borja_042看到如何刪除空心和添加/刪除標題的更新 – Jaap

+0

這是完全完美的!我用代碼編輯我的帖子。謝謝! –