knitr::opts_chunk$set(echo = FALSE, eval = TRUE, warning=FALSE, message=FALSE, fig.width=7)

Getting started

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)

1. What is the number of movies produced per year? Use the black-and-white theme with this plot. Can you notice changes when you compare your answers, with and without the requested theme?

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

2. What is the number of movies produced per year per genre (action, animation ect)? Use the black-and-white theme customised to: relocate legend position; remove legend background (if any); remove panel.grid; etc. (if you wish)

# 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()
  )

3. Is there a difference on rating depending on genre? Use the black-and-white theme customised to get the 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))

4. Does the length of the movie change per genre? (you may use facet_wrap)

ggplot(movies, aes(x=length)) +
  geom_density(fill="red", alpha=0.4) +
  xlim(0,300) + facet_wrap(~ Genre)


statcourses/BristolVis documentation built on Jan. 31, 2021, 9:24 p.m.