Creating piechart from a count column with percentage as labels

by Borja_042   Last Updated December 27, 2017 20:26 PM

I have created a list with a count of the values of 1 column:

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

And I want to make a piechart with the percentages, not with the counts out of it. I have tried to take that list to a df and then using something like this:

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

But I am struggling a lot, maybe that option is already implemented on ggplot2...

I have tried also this:

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

But it gives me a count, not the percentages of the categorical variable. After that I would just need to entitle the plot and that's it.

Thanks in advance!!



Answers 1


Calculate the percentage:

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

Then plot:

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()

which gives:

enter image description here


Used data:

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))
Jaap
Jaap
December 27, 2017 20:09 PM

Related Questions




Using R for 3 variable stacked barplot

Updated May 30, 2017 19:26 PM

barplot2 error on Confidence intervals?

Updated April 12, 2015 01:11 AM