Plotting two plots in a single row using ggplot in R

r
ggplot2

#1

Hi there,

I encountered a problem today while trying to plot two ggplots side by side.
I tried using the par command but it seemed to work only for base plotting package and not lattice and ggplot.

Here is what I tried.

library(data.table)
setwd("F:\\ML_P\\course 2")
data<-fread("crime rate.csv")
View(data)

par(mfrow=c(2,2))

library(ggplot2)
g1<-ggplot(data,aes(HousePrice,CrimeRate))+geom_point()+geom_smooth(method = "lm")


data1<-subset(data,CrimeRate<200)
g2<-ggplot(data1,aes(HousePrice,CrimeRate))+geom_point()+geom_smooth(method = "lm")+ylim(0,300)

Am I doing anything wrong ? Or is par incompatible with tht lattice and ggplot packages.

Thanks

Neeraj


#2

Hi NSS,

As per my knowledge its difficult to plot 2 ggplots in same page with out using any external package
I tried with “cowplot” package its worked for me
Plot_grid is the function in cowplot

Example :

data =mtcars

g1<-ggplot(mtcars,aes(mpg,hp))+geom_point()

g2<-ggplot(mtcars,aes(mpg,hp,fill=gear))+geom_point()

library(cowplot)
plot_grid(g1, g2, labels=c(“mpg”, "hp "), ncol = 2, nrow = 1)

I hope this solution might work for you
May be there are different ways but i used this method to plot
Please try like this and let me know it it works for you

Thanks & Regards
Raghavendra


#3

Hi @NSS

One other package gridExtra simple as plot grid

Example:

dspfreq<- ggplot(data=allsnapshots, aes(x=numbsnaps)) +
geom_density(color=“blue”, fill=“lightblue”, alpha=.2) +
ylab(“Density”) +
xlab(“Number of snapshots (months)”) +
ggtitle(“Debts life span”)

dspcumfreq<- ggplot(data=allsnapshots, aes(x=numbsnaps)) +
stat_ecdf(geom=“step”, color=“blue”) +
ylab(“Cumulative Frequency”) +
xlab(“Number of snapshots (months)”) +
ggtitle(“Cumulative Frequency”)

grid.arrange(dspfreq ,dspcumfreq , ncol=2)

Hope this help
Alain


#4

You need to add’ +facet_wrap() ’ to your ggplot()

facet_wrap(facets, nrow = NULL, ncol = NULL, scales = “fixed”,
shrink = TRUE, labeller = “label_value”, as.table = TRUE,
switch = NULL, drop = TRUE, dir = “h”)