In the previous post ggplot2 package (Part1) (https://dataworldblog.blogspot.com.es/2017/07/ggplot2-package-part1.html) we cover some plots using
ggplot2
, here we will cover Barplots along with how to plot different plots together.- Barplot:
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 3.4.1
# Barplot
one <- span=""> ggplot(chickwts, aes(x=feed)) +
geom_bar()+
xlab("Feed") +
ylab("Count") +
ggtitle("Chickwts1")
one->
two <- span=""> ggplot(chickwts, aes(x=feed)) +
geom_bar(color="red", fill = "pink", width=0.5) +
xlab("Feed") +
ylab("Count")
ggtitle("Chickwts2")
two->
- Grid Lines
three <- span="">ggplot(chickwts, aes(x=feed)) +
geom_bar(fill='steelblue', width = 0.3) +
coord_flip() +
xlab("Feed") +
ylab("Count") +
theme(panel.background = element_rect(fill = 'lightblue'),
panel.grid.major = element_line(colour = "pink", size=1),
panel.grid.minor = element_line(colour = "red", size=1)) +
ggtitle("Chickwts3")
three->
- Margins and Annotations
library(grid)
grob = grobTree(textGrob("This is the annotation, \n Placed at x= 0.5,y=0.5", x=0.5, y=0.5, hjust=0,gp=gpar(col="purple", fontsize=10, fontface="bold")))
four <- span="">ggplot(chickwts, aes(x=feed)) +
geom_bar(fill='steelblue', width = 0.4) +
coord_flip() +
xlab("Feed") +
ylab("Count") +
theme(plot.background=element_rect(fill="lightblue"), plot.margin = unit(c(2, 5, 2, 2), "mm")) +
annotation_custom(grob)+
ggtitle("Chickwts4")
four->
- Multiple plots
Usually to combine multiple plots into one overall graph in R we use
par()
or layout()
functions, but when using the package ggplot2 these functions do not work. A good solution to fix this easily is to use the package gridExtra
, which has a function grid.arrange()
that allows to combine different plots into one:library(gridExtra)
## Warning: package 'gridExtra' was built under R version 3.4.1
grid.arrange(one, two, three)
grid.arrange(one, two, three, ncol = 3)
grid.arrange(one, two, three, ncol = 2, nrow = 2)
grid.arrange(one, two, three, four, ncol = 2, nrow = 2)
grid.arrange(one, arrangeGrob(two,three, ncol=2), heights=c(1.5/4, 1.5/4), ncol=1, top= 'Multiple graphs in one page', bottom= 'bottom', left = 'left', right ='right')