Shakil Ahmed Shaon
Shakil Ahmed Shaon

Reputation: 119

How to edit the labels of the donut chart using ggplot2 of R?

I am trying to create a donut chart using the following codes -

library (ggplot2)
data = data.frame (
 category = c("No/Minimal", "Mild", "Moderate", "Moderately Severe", "Severe"),
 count = c(27,21,179,67,32))

data$fraction = data$count/sum(data$count)
data$ymax = cumsum(data$fraction)
data$ymin = c(0, head(data$ymax, n=-1))

data$category = factor (data$category, levels = c("No/Minimal", "Mild", "Moderate", "Moderately Severe", "Severe"))

p = ggplot(data, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) +
 geom_rect() +
 coord_polar(theta="y") +
 xlim(c(2, 4))
p

dep<-p + scale_fill_brewer("Depression Level") + theme_void() +
 theme(axis.text.x=element_blank()) + theme(legend.position=c(.5, .5)) + ggtitle("") +
 theme(panel.grid=element_blank()) +
 theme(axis.text=element_blank()) +
 theme(axis.ticks=element_blank()) +
 theme(legend.title = element_text(size=14, face="bold")) +
 theme(legend.text = element_text(size = 12, face = "bold"))
dep
dep+geom_label(aes(label=paste(fraction*100,"%"),x=3.5,y=(ymin+ymax)/2),inherit.aes = TRUE, show.legend = FALSE)

It gives me an output like this - enter image description here

But I want to present the percentage like this 9.8%, 54.9%, 20.5%, 6.4% ...

what should I add or change here in this code?

Upvotes: 1

Views: 755

Answers (2)

Ben
Ben

Reputation: 30494

How about using round with 3 digits in your geom_label?

geom_label(aes(label=paste(round(fraction, digits = 3)*100,"%"),x=3.5,y=(ymin+ymax)/2),inherit.aes = TRUE, show.legend = FALSE)

To make bold and larger, change fontface and size:

geom_label(aes(label=paste(round(fraction, digits = 3)*100,"%"),x=3.5,y=(ymin+ymax)/2),inherit.aes = TRUE, show.legend = FALSE, 
               fontface = "bold", size = 5)

Upvotes: 1

nurandi
nurandi

Reputation: 1618

Change label in the last line to:

paste0(formatC(100*fraction, digits=1, format="f"), "%")
dep + geom_label(aes(label=paste0(formatC(100*fraction, digits=1, format="f"), "%"),x=3.5,y=(ymin+ymax)/2),
               inherit.aes = TRUE, show.legend = FALSE)

label

Upvotes: 3

Related Questions