
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Facetted Plot with One Facet Displaying All Data using ggplot2 in R
To create facetted plot with one facet displaying all data using ggplot2 in R, we can follow the below steps −
- First of all, create a data frame.
- Then, create facetted plot using facet_grid function.
- After that, create the facetted plot with margins argument set to TRUE to display the plot with all data.
Create the data frame
Let's create a data frame as shown below −
x<-round(rexp(25,1.25),2) y<-round(rexp(25,1.89),2) Grp<-sample(LETTERS[1:3],25,replace=TRUE) df<-data.frame(x,y,Grp) df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y Grp 1 2.32 0.47 C 2 0.96 0.01 C 3 0.34 0.49 A 4 1.11 0.75 C 5 0.57 0.63 C 6 0.47 0.38 B 7 0.69 0.06 A 8 1.12 1.66 C 9 0.62 0.81 C 10 0.05 0.60 C 11 0.50 0.05 A 12 0.06 0.18 A 13 0.08 1.30 C 14 2.22 0.13 C 15 0.03 0.13 C 16 0.06 0.24 C 17 0.57 1.04 A 18 0.50 0.09 C 19 1.10 0.36 B 20 0.10 0.00 B 21 1.28 0.42 A 22 1.56 0.34 A 23 1.38 0.15 A 24 0.54 0.03 B 25 1.81 1.85 A
Create the facetted plot
Use facet_grid function to create the facetted scatterplot between x and y −
x<-round(rexp(25,1.25),2) y<-round(rexp(25,1.89),2) Grp<-sample(LETTERS[1:3],25,replace=TRUE) df<-data.frame(x,y,Grp) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+facet_grid(~Grp)
Output
Create the facetted plot displaying one facet with all data
Using margins argument to create the facetted plot displaying one facet with all data as shown below −
x<-round(rexp(25,1.25),2) y<-round(rexp(25,1.89),2) Grp<-sample(LETTERS[1:3],25,replace=TRUE) df<-data.frame(x,y,Grp) library(ggplot2) ggplot(df,aes(x,y))+geom_point()+facet_grid(~Grp,margins=TRUE)
Output
Advertisements