![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Advertisements