I have created a donut chart in R using ggplot2 package. Now I need to add "0" decimal in the "No" slice. It is now shown in the graph as "74%" - but I want to present this as "74.0%". The followings are the codes and the graph -
df = data.frame(Dep = c("No",
"Mild",
"Moderate",
"Moderately Severe",
"Severe"),
Percentage = c(74.0, 12.8, 9.4, 2.3, 1.6),
Count = c(284, 49, 36, 9, 6))
df$Dep = factor(df$Dep, levels = c("No",
"Mild",
"Moderate",
"Moderately Severe",
"Severe"))
df = df %>%
arrange(desc(Dep)) %>%
mutate (Percentage) %>%
mutate (ypos = cumsum(Percentage)-0.5*Percentage)
donut= ggplot(df, aes(x =2, y=Percentage,fill=Dep))+
geom_bar(stat="identity")+
coord_polar("y", start=180)+
scale_fill_brewer(palette = "Set2")+
theme_void()+
geom_text(aes(y=ypos, label=paste0(round(Percentage,1),"%")),
color = "black", size=4.5, angle = 0)+
xlim(0.25, 2.5)+theme(legend.position=c(.5, .5))+
theme(panel.grid=element_blank()) +
theme(axis.text=element_blank()) +
theme(axis.ticks=element_blank()) +
theme(legend.title = element_text(size=18, face="bold",)) +
theme(legend.text = element_text(size = 14, face = "bold"))
donut
I am searching for this solution but cannot be able to find anything useful. Thanks in advance. Your help will be much appreciated.
You just need to use sprintf()
. Please find below a reprex.
Reprex
library(ggplot2)
library(dplyr)
#>
#> Attachement du package : 'dplyr'
#> Les objets suivants sont masqués depuis 'package:stats':
#>
#> filter, lag
#> Les objets suivants sont masqués depuis 'package:base':
#>
#> intersect, setdiff, setequal, union
df = data.frame(Depression = c("No",
"Mild",
"Moderate",
"Moderately Severe",
"Severe"),
Percentage = c(74.0, 12.8, 9.4, 2.3, 1.6),
Count = c(284, 49, 36, 9, 6))
df$Depression = factor(df$Depression, levels = c("No",
"Mild",
"Moderate",
"Moderately Severe",
"Severe"))
df = df %>%
arrange(desc(Depression)) %>%
mutate (Percentage) %>%
mutate (ypos = cumsum(Percentage)-0.5*Percentage)
donut= ggplot(df, aes(x =2, y=Percentage,fill=Depression))+
geom_bar(stat="identity")+
coord_polar("y", start=180)+
scale_fill_brewer(palette = "Pastel2")+
theme_void()+
geom_text(aes(y=ypos, label=paste0(sprintf("%.1f",Percentage),"%")),
color = "black", size=4.5, angle = 0)+
xlim(0.25, 2.5)+theme(legend.position=c(.5, .5))+
theme(panel.grid=element_blank()) +
theme(axis.text=element_blank()) +
theme(axis.ticks=element_blank()) +
theme(legend.title = element_text(size=18, face="bold",)) +
theme(legend.text = element_text(size = 14, face = "bold"))
donut
Created on 2022-03-05 by the reprex package (v2.0.1)