I am trying to learn how to combine different types of graphs together in the R programming language. Suppose I have the following data:
library(dplyr)
library(ggplot2)
date= seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
var <- rnorm(731,10,10)
group <- sample( LETTERS[1:4], 731, replace=TRUE, prob=c(0.25, 0.22, 0.25, 0.25) )
data = data.frame(date, var, group)
data$year = as.numeric(format(data$date,'%Y'))
data$year = as.factor(data$year)
I summarized this data making different types of graphs. For example:
1) Pie Charts:
###Pie
Pie_2014 <- data %>% filter((data$year == "2014"))
Pie_2014 %>%
group_by(group) %>%
summarise(n = n())
Pie_2014_graph = ggplot(Pie_2014, aes(x="", y=n, fill=group)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +ggtitle( "Pie Chart 2014")
Pie_2015 <- data %>% filter((data$year == "2015"))
Pie_2015 %>%
group_by(group) %>%
summarise(n = n())
Pie_2015_graph = ggplot(Pie_2015, aes(x="", y=n, fill=group)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +ggtitle( "Pie Chart 2015")
Pie_total = data %>%
group_by(group) %>%
summarise(n = n())
Pie_total_graph = ggplot(data, aes(x="", y=n, fill=group)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +ggtitle( "Pie Chart Average")
Bar Plots:
Bar_years = data %>%
group_by(year, group) %>%
summarise(mean = mean(var))
Bar_years_plot = ggplot(Bar_years, aes(fill=group, y=mean, x=year)) +
geom_bar(position="dodge", stat="identity") + ggtitle("Bar Plot All Years")
Bar_total = data %>%
group_by(group) %>%
summarise(mean = n())
Bar_total_plot = ggplot(Bar_total, aes(x=group, y=mean, fill=group)) +
geom_bar(stat="identity")+theme_minimal() + ggtitle("Bar Plot Average")
Time Series Plots:
New <- data %>%
mutate(date = as.Date(date)) %>%
group_by(group, month = format(date, "%Y-%m")) %>%
summarise( Mean = mean(var, na.rm = TRUE), Count = n())
#Plot
ts_1 <- ggplot(New) +
geom_line(aes(x=month, y=Mean, colour=group,group=1))+
scale_colour_manual(values=c("red","green","blue", "purple"))+
theme(axis.text.x = element_text(angle=90)) + ggtitle("time seres 1")
ts_2 <- ggplot(New) +
geom_line(aes(x=month, y=Count, colour=group,group=1))+
scale_colour_manual(values=c("red","green","blue", "purple"))+
theme(axis.text.x = element_text(angle=90)) + ggtitle("time seres 2")
All these graphs work perfectly. Now I am looking for a better way to present them.
My question: Is it possible to neatly arrange all these graphs into a window using R and ggplot2?
For example:
Row 1: All Pie Charts (Pie_2014_graph, Pie_2015_graph, pie_total_graph)
Row 2: All Bar Graphs (Bar_years_plot, Bar_total_plot)
Row 3: All Time Series Graphs (ts_1, ts_2)
Right now, I creating all these graphs individually, pasting them into MS Paint and manually rearranging them.
Something like this?
All help is greatly appreciated.
Thanks
See Question&Answers more detail:
os