从计数列创建饼图,百分比作为标签

时间:2017-12-27 19:58:30

标签: r dataframe ggplot2 pie-chart

我创建了一个列表,其中包含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")

但它给了我一个计数,而不是分类变量的百分比。在那之后,我只需要赋予情节权利,就是这样。

1 个答案:

答案 0 :(得分: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))