- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
To Continue Learning Please Login
Login with Google