knitr::opts_chunk$set(echo = FALSE, eval = TRUE, warning=FALSE, message=FALSE, fig.width=7)
We aim to practice on how to use theme and facet concepts in ggplot2, we'll use the same plots created in the previous practical session on advanced graphics.
Firstly, We should load the ggplot2
library("ggplot2")
Next, we load the movies data set
# Details of the movies dataset can be displayed by: library(ggplot2movies) data(movies, package="ggplot2movies") ?movies
When loading in data, it's a good idea to check some basic characteristics:
head(movies)
g = ggplot(data=movies, aes(x=year)) g1 = g + geom_histogram(binwidth = 1, fill="#2b8cbe", alpha=0.6) + xlab("Year") + ylab("Number of movies produced") + theme_bw()
g1
# TIP: You need first to create a genre variable: genre <- rep(0, nrow(movies)) for(i in 18:24) { genre[movies[,i]==1] <- names(movies)[i] }; genre[genre==0] <- "Unknown" movies$Genre <- genre
clr <- c('#8dd3c7','#ffffb3','#bebada','#fb8072','#80b1d3','#fdb462','#b3de69', '#000000') ggplot(movies, aes(x=year, fill=Genre)) + geom_histogram(binwidth=1) + scale_fill_manual(values = clr) + xlab("Year") + ylab("Number of movies produced") + ylim(0,1900) + xlim(1890,2005) + theme_bw() + theme( legend.position = c(0.2,0.7), legend.background = element_blank(), legend.key = element_blank(), panel.background = element_blank(), strip.background = element_blank(), panel.border = element_blank(), plot.background = element_blank(), axis.line = element_blank(), panel.grid = element_blank() )
axis.text: bold, of 12 font size; with an angle of 45; with horizontal justification to right (hjust = 1)ggplot(movies, aes(x=factor(Genre), y=rating)) + xlab("") + ylab("Rating (out of 10") + geom_violin(fill="red", alpha=0.4) + stat_summary(fun.y = median, geom='point') + theme_bw() + theme(axis.text=element_text(face='bold', size = 12, angle = 45, hjust = 1))
facet_wrap)ggplot(movies, aes(x=length)) + geom_density(fill="red", alpha=0.4) + xlim(0,300) + facet_wrap(~ Genre)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.