- 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 plot for one categorical variable in an R dataframe.
To create stacked bar plot for one categorical variable in an R data frame, we can use ggplot function and geom_bar function of ggplot2 and provide 1 as the X variable inside aes.
For Example, if we have a data frame called df that contains a one categorical column say C and one numerical column Num then we can create the stacked bar plot by using the below command −
ggplot(df,aes(1,Num,fill=C))+geom_bar(stat="identity")
Example
Following snippet creates a sample data frame −
x<-c("Male","Female","Unknown") Count<-c(45,38,20) df<-data.frame(x,Count) df
The following dataframe is created
x Count 1 Male 45 2 Female 38 3 Unknown 20
To load ggplot2 package and create bar plot for values in df on the above created data frame, add the following code to the above snippet −
x<-c("Male","Female","Unknown") Count<-c(45,38,20) df<-data.frame(x,Count) library(ggplot2) ggplot(df,aes(x,Count))+geom_bar(stat="identity")
Output
If you execute all the above given snippets as a single program, it generates the following Output −
To create stacked bar plot for values in df on the above created data frame, add the following code to the above snippet −
x<-c("Male","Female","Unknown") Count<-c(45,38,20) df<-data.frame(x,Count) library(ggplot2) ggplot(df,aes(1,Count,fill=x))+geom_bar(stat="identity")
Output
If you execute all the above given snippets as a single program, it generates the following Output −
- Related Articles
- How to create the stacked bar plot using ggplot2 in R with labels on the plot?
- How to create stacked bar plot in which each bar sum to 1 or 100% in R?
- How to create a stacked bar plot with vertical bars in R using ggplot2?
- How to create a stacked bar chart for my DataFrame using Seaborn in Matplotlib?
- How to create a frequency column for categorical variable in an R data frame?
- Create bar plot of one column in an R data frame using ggplot2.
- How to create a point chart for categorical variable in R?
- How to create stacked bar chart using ggvis in R?
- How to create horizontal stacked bar chart using ggvis in R?
- How to create stacked plot with density using ggplot2 in R?
- How to create a bar plot using ggplot2 with one bar having black border in R?
- How to create horizontal lines for each bar in a bar plot of base R?
- Create bar plot for grouped data of two columns in base R.
- Python Pandas - Plot a Stacked Horizontal Bar Chart
- Create stacked bar chart with percentages on Y-axis using ggplot2 in R.
