How to create the stacked bar plot using ggplot2 in R with labels on the plot?


The creation of stacked bar plot using ggplot2 can be done with the help of position="stack" argument inside geom_bar function. If we want to create the stacked bar plot then geom_text function will be used with the same position argument and the aes to define the labels as shown in the below example.

Example

 Live Demo

Consider the mtcars data −

head(mtcars)

Output

mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

Example

 Live Demo

df<−data.frame(with(mtcars,table(cyl,gear)))
df

Output

cyl gear Freq
1 4 3 1
2 6 3 2
3 8 3 12
4 4 4 8
5 6 4 4
6 8 4 0
7 4 5 2
8 6 5 1
9 8 5 2

Loading ggplot2 package and creating the stacked bar plot −

Example

library(ggplot2)

Output

ggplot(df,aes(gear,fill=cyl))+geom_bar(aes(weight=Freq),position="stack")+geom_text(position="stack",aes(gear,Freq,label=cyl),size=5)

Output

Updated on: 08-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements