Rawshn
Rawshn

Reputation: 37

Drawing Pie3D Graph in R

I was plotting a data.frame in R in a pie graph. Here is the code

library(plotrix)
piepercent<- round(100*cause_wise$suicides/sum(cause_wise$suicides), 1)
png(file = "plots/cause suicide.png")
pie3D(cause_wise$suicides,labels = piepercent,explode = 0.1, 
  main = "Suicide by Gender(in percentages)")
#legend("topright", cause, cex = 0.8, fill = rainbow(length(cause)))
dev.off()

The data.frame which I am trying to plot here has 38 values, I want to leave out those values which do not contribute significantly to the piepercent into one big area say less than 2%. Is there a way I can do this?

Here is how the graph looks like:

Pie-Chart

Upvotes: 0

Views: 2403

Answers (1)

zx8754
zx8754

Reputation: 56259

Aggregate the ones less than threshold into one category, then plot:

library(plotrix)
library(dplyr)

# dummy data
cause_wise <- data.frame(suicides = c(2, 3, 1, 50, 1, 50, 45))

# sum values where percentage is less than 2%
plotDat <- cause_wise %>% 
  mutate(grp = ifelse(suicides/sum(suicides) < 0.02, "tooSmall", row_number())) %>% 
  group_by(grp) %>% 
  summarise(suicides = sum(suicides)) %>% 
  select(-grp) %>% 
  ungroup()

# set label and color(grey for <2%)
piepercent <- round(100 * plotDat$suicides/sum(plotDat$suicides), 1)
piecol <- c(rainbow(length(piepercent) - 1 ), "grey")

# why oh why 3D pie chart...
pie3D(plotDat$suicides,
      labels = piepercent, 
      explode = 0.1,
      col = piecol,
      main = "Suicide by Gender (in percentages)")

enter image description here

Upvotes: 1

Related Questions