I wanted to have a dodge barplot in ggplot2 that show whether a person has savings or not and all this by another variable, region. Since there are missing data I want to include them as another category in the plot and in that way every region would have three bars: one for having, one for not having and one for missing data. Now I made a plot that shows exactly what I want for which I picked up some code on the internet because I really couldn’t do it correctly.
The only problem is that now it shows the percentages on the tops of the bars which feature I don’t want.
How do I get rid of it? Or how can I round it up at least?enter image description here
ggplot(adatok, aes(x=as.factor(region), fill=as.factor(savings)))+
geom_bar(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..]), position="dodge" ) +
geom_text(aes(label=scales::percent(..count../tapply(..count.., ..x.. ,sum)[..x..]),
y=..count../tapply(..count.., ..x.. ,sum)[..x..] ),
stat="count", position=position_dodge(0.9), vjust=-0.5)+
scale_y_continuous(labels = scales::percent)
>Solution :
I’ll use mtcars (with its cyl and gear) to demonstrate two options.
Starting point:
library(ggplot)
data("mtcars")
ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(gear)))+
geom_bar(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..]), position="dodge" ) +
geom_text(aes(label=scales::percent(..count../tapply(..count.., ..x.. ,sum)[..x..]),
y=..count../tapply(..count.., ..x.. ,sum)[..x..] ),
stat="count", position=position_dodge(0.9), vjust=-0.5)+
scale_y_continuous(labels = scales::percent)
-
If you don’t want the literal percent signs, remove
scales::percent(and see numbers like0.72727272727272727) orround(100*., 1)it:ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(gear)))+ geom_bar(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..]), position="dodge" ) + geom_text(aes(label=round(100*(..count../tapply(..count.., ..x.. ,sum)[..x..]), 1), y=..count../tapply(..count.., ..x.. ,sum)[..x..] ), stat="count", position=position_dodge(0.9), vjust=-0.5)+ scale_y_continuous(labels = scales::percent) -
If you don’t want the numbers at all, remove the
geom_text(.)completely.ggplot(mtcars, aes(x=as.factor(cyl), fill=as.factor(gear)))+ geom_bar(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..]), position="dodge" ) + scale_y_continuous(labels = scales::percent)


