This practical follows the previous basic introduction to ggplot2. It allows to go further with
ggplot2: annotation, theme customization, color palette, output formats, scales, and more.
The following libraries are needed all along the practical. Install them with install.packages() if you do not have them already. Then load them with library().
Q1.1 The code below builds a basic histogram for Rbnb apartment prices on the French Riviera. It shows only value under 300 euros. Add code to:
ggtitle()xlab() and ylab()xlim() and ylim()# Libraries
library(ggplot2)
# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/1_OneNum.csv", header=TRUE)
# Make the histogram
data %>%
filter( price<300 ) %>%
ggplot( aes(x=price)) +
geom_histogram() +
ggtitle("Night price distribution of Airbnb appartements") +
xlab("Night price") +
ylab("Number of apartments") +
xlim(0,400)All ggplot2 chart components can be changed using the theme() function. You can see a complete list of components in the official documentation.
Note: components are changed using different functions: element_text(), element_line() for lines and so on..
Q1.2 Reproduce the previous histogram and change:
plot.titleaxis.title.xpanel.grid.major# Make the histogram
data %>%
filter( price<300 ) %>%
ggplot( aes(x=price)) +
geom_histogram() +
ggtitle("Night price distribution of Airbnb appartements") +
xlab("Night price") +
ylab("Number of apartments") +
xlim(0,400) +
theme(
plot.title = element_text(size=13, color="orange"),
axis.title.x = element_text(size=13, color="purple"),
panel.grid.major = element_line(colour = "red")
)
Q1.3 ggplot2 offers a set of pre-built themes. Try the followings to see which one you like the most:
theme_bw()theme_dark()theme_minimal()theme_classic()See a complete list here.
# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/1_OneNum.csv", header=TRUE)
# Make the histogram
data %>%
filter( price<300 ) %>%
ggplot( aes(x=price)) +
geom_histogram(fill="#69b3a2", color="#e9ecef", alpha=0.9) +
ggtitle("Night price distribution of Airbnb appartements") +
theme_classic()
Q1.4 The hrbrthemes package provides my favourite style. Install the package, load it, and apply the theme_ipsum(). Documentation is here.
# Libraries
library(tidyverse)
library(hrbrthemes)
library(viridis)
# Load dataset from github
data <- read.table("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/1_OneNum.csv", header=TRUE)
# Make the histogram
data %>%
filter( price<300 ) %>%
ggplot( aes(x=price)) +
stat_bin(breaks=seq(0,300,10), fill="#69b3a2", color="#e9ecef", alpha=0.9) +
ggtitle("Night price distribution of Airbnb appartements") +
theme_ipsum()