How to display text in bar plot in the middle using ggplot2 in R?


To display text in bar plot in the middle using ggplot2 in R, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use ggplot function and geom_bar function to create the bar plot along with geom_text function to display the text in the middle

Example

Create the data frame

Let’s create a data frame as shown below −

x<-LETTERS[1:4]
freq<-c(24,28,21,30)
df<-data.frame(x,freq)
df

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

  x freq
1 A 24
2 B 28
3 C 21
4 D 30

Create the bar plot and display text in the middle

Using ggplot function and geom_bar function to create the bar plot for the data stored in data frame df along with geom_text function to display the text of freq column in the middle of bars −

x<-LETTERS[1:4]
freq<-c(24,28,21,30)
df<-data.frame(x,freq)
library(ggplot2)

ggplot(df,aes(x,freq))+geom_bar(stat="identity")+geom_text(aes(label=freq),color="white",size=5,position=position_stack(vjust=0.5))

Output

Updated on: 11-Nov-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements