- 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

# How to visualize two categorical variables together in R?

The categorical variables can be easily visualized with the help of mosaic plot. In a mosaic plot, we can have one or more categorical variables and the plot is created based on the frequency of each category in the variables. To create a mosaic plot in base R, we can use mosaicplot function. The categories that have higher frequencies are displayed by a bigger size box and the categories that have less frequency are displayed by smaller size box.

Consider the below data frame −

## Example

x1<-sample(c("Lower","Middle","Upper"),20,replace=TRUE) x2<-sample(c("Male","Female"),20,replace=TRUE) df<-data.frame(x1,x2) df

## Output

x1 x2 1 Lower Female 2 Upper Male 3 Upper Male 4 Lower Male 5 Lower Female 6 Middle Female 7 Middle Female 8 Middle Female 9 Upper Female 10 Middle Female 11 Lower Female 12 Lower Male 13 Middle Male 14 Lower Male 15 Upper Female 16 Upper Female 17 Upper Male 18 Upper Male 19 Middle Male 20 Middle Female

Creating mosaic plot for the above data −

## Example

mosaicplot(x2~x1,data=df)

## Output

## Example

mosaicplot(x2~x1,data=df,col=c("Blue","Red"))

## Output

- Related Articles
- How to detect multicollinearity in categorical variables using R?
- How to plot two histograms together in R?
- How to plot categorical variables in Matplotlib?
- Differentiate between categorical and numerical independent variables in R.
- How to create a table of sums of a discrete variable for two categorical variables in an R data frame?
- How to count the number of rows for a combination of categorical variables in R?
- How to create two lines using ggplot2 based on a categorical column in R?
- Python Pandas - Group the swarms by two categorical variables with Seaborn
- How to apply two sample t test using a categorical column in R data frame?
- Correlation Between Categorical and Continuous Variables
- How to find the summary by categorical variable in R?
- How to filter data frame by categorical variable in R?
- How to find the two factor interaction variables in an R data frame?
- How to test for significant relationship between two categorical columns of an R data frame?
- How to visualize a data frame that contains missing values in R?

Advertisements