- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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 include a factor level in bar blot using ggplot2 in R if that level has a frequency zero.
In research, sometimes we get a count of zero for a particular level of a factor variable but we might want to plot that in the bar plot so that anyone who look at the plot can easily understand what is missing and compare all the factor levels. In ggplot2, it can be done with the help of scale_x_discrete function.
> x<-factor(rep(c("S1","S2","S3","S4"),times=5)) > df<-data.frame(x)
Suppose you have a factor level S5 as well but the frequency for S5 is zero as shown below −
> df$x<-factor(df$x,levels=c("S1","S2","S3","S4","S5")) > df$x  S1 S2 S3 S4 S1 S2 S3 S4 S1 S2 S3 S4 S1 S2 S3 S4 S1 S2 S3 S4 Levels: S1 S2 S3 S4 S5
Loading ggplot2 package −
Now when we plot the bar plot the fifth level is not there −
The R command to plot all the factor levels is as shown below −
> ggplot(df,aes(x))+geom_bar()+ + scale_x_discrete(drop=FALSE)
- How to create a new level using unique levels of a factor in R data frame?
- How to create a subset for a factor level in an R data frame?
- How to set a level of a factor column in an R data frame to NA?
- How to create a horizontal bar graph using ggplot2 in R?
- Extract a particular level from factor column in an R data frame.
- How to create a bar plot with ggplot2 using stat_summary in R?
- How to include a zero with tick in base R plot?
- How to create a frequency table in R that includes zero frequency for value that are not available?
- How to reverse the bars of a bar plot a using ggplot2 in R?
- How to create a bar plot using ggplot2 with one bar having black border in R?
- How to create a bar chart for single vector using ggplot2 in R?
- How to create transparent bar plot using ggplot2 in R?
- How to select the first row for each level of a factor variable in an R data frame?
- How to create a stacked bar plot with vertical bars in R using ggplot2?
- How to change the Y-axis values in a bar plot using ggplot2 in R?