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

问题描述 投票:3回答:1

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

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

r dataframe ggplot2 pie-chart
1个回答
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))
© www.soinside.com 2019 - 2024. All rights reserved.