Home > Blockchain >  Percentage inside the pie chart instead of count
Percentage inside the pie chart instead of count

Time:04-19

My data frame

dput(d)
structure(list(x = c("Organonitrogen compound metabolic process", 
"Cellular process", "Nitrogen compound metabolic process", "Primary metabolic process", 
"Organic substance biosynthetic process", "Metabolic process", 
"Cellular nitrogen compound biosynthetic process", "Cellular metabolic process", 
"Organic substance metabolic process", "Cellular biosynthetic process"
), freq = c(71, 119, 87, 89, 52, 94, 42, 89, 89, 49)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

The code I'm running to generate the pie chart

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 = 'Pathway Pie chart', subtitle = 'percentages')  
  coord_polar(theta = "y")  
  theme_minimal()

I get something like this

my image

But I would like to see something like this.

Any help or suggestion would be really appreciated

this figure with percentage inside the plot

CodePudding user response:

scales::percent() is designed for this. Try

geom_text(aes(label = scales::percent(freq/sum(freq), 1)),
          position = position_stack(vjust = 0.5))  

Because you have calculated the percentage as perc, you can pass it into percent() directly. (Beware of its args accuracy and scale. In your case they both should be 1)

geom_text(aes(label = scales::percent(perc, 1, 1)),
          position = position_stack(vjust = 0.5))  

You can search ?scales::percent to see more args to adjust.

CodePudding user response:

You can use theme_void to remove axis and ticks and sprintf to display the percent symbol.

ggplot(data = d, aes(x = 0, y = freq, fill = x))   
  geom_bar(stat = "identity")  
  geom_text(aes(label =  sprintf("%d%%",perc)),
            position = position_stack(vjust = 0.5),
            size = 3)  
  scale_x_continuous(expand = c(0,0))  
  labs(fill = 'Type', x = NULL, y = NULL, title = 'Pathway Pie chart', subtitle = 'percentages')  
  coord_polar(theta = "y")  
  theme_void()

enter image description here

  • Related