- Trending Categories
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
Create stacked bar chart with percentages on Y-axis using ggplot2 in R.
To create stacked bar chart with percentages on Y-axis using ggplot2 in R, we can use fill argument inside geom_bar and put the second categorical variable with position set to fill.
For Example, if we have a data frame called with two categorical columns say C1 and C2 then we can create stacked bar chart with percentages on Y-axis using the below mentioned command −
ggplot(df,aes(C1))+geom_bar(aes(fill=C2),position="fill")
Example
Following snippet creates a sample data frame −
f1<-sample(LETTERS[1:3],20,replace=TRUE) f2<-sample(letters[1:2],20,replace=TRUE) df<-data.frame(f1,f2) df
The following dataframe is created
f1 f2 1 B b 2 C a 3 A b 4 A a 5 A a 6 C a 7 B a 8 B a 9 C b 10 B a 11 A a 12 C a 13 A b 14 C b 15 C a 16 B b 17 A b 18 B a 19 A a 20 C a
To load ggplot2 package and create stacked bar chart for columns f1 and f2 with percentages on Y-axis on the above created data frame, add the following code to the above snippet −
f1<-sample(LETTERS[1:3],20,replace=TRUE) f2<-sample(letters[1:2],20,replace=TRUE) df<-data.frame(f1,f2) library(ggplot2) ggplot(df,aes(f1))+geom_bar(aes(fill=f2),position="fill")
Output
If you execute all the above given snippets as a single program, it generates the following Output −
- Related Articles
- How to create cumulative sum chart with count on Y-axis in R using ggplot2?
- How to create a bar plot using ggplot2 with percentage on Y-axis in R?
- How to create stacked bar chart using ggvis in R?
- How to create bar chart using ggplot2 with chart sub-title in R?
- How to create the stacked bar plot using ggplot2 in R with labels on the plot?
- How to create horizontal stacked bar chart using ggvis in R?
- How to create a stacked bar plot with vertical bars in R using ggplot2?
- How to create the bar chart with ggplot2 using color brewer in R?
- How to display count on Y-axis for line chart using ggplot2 in R?
- Create ggplot2 graph with reversed Y-axis and X-axis on top in R.
- How to create a stacked bar chart using JavaFX?
- How to create stacked plot with density using ggplot2 in R?
- How to create a bar chart for single vector using ggplot2 in R?
- How to change the gridlines of Y-axis on a chart created by using ggplot2 in R?
- How to create a histogram with Y-axis values as count using ggplot2 in R?

Advertisements