Introduction
We are going to reproduce three different plots, of which we are only given the data set and the final image file. Each of them has two versions:
- The first version is a plot made just using the layer functions of
ggplot2and leaving everything else with the defaults. This is, usingggplot,geom_*,stat_*andannotate_*functions (click on the image to see it bigger).
- The second version builds from the first plot to create a more
complex display with customized
scales_*,coord_*,facet_*ortheme_*. Helper functions such aslabs()orguides()could also be used (click on the image to see it bigger).
: ggplot2 will
automatically load all three data sets used in this practical.
Organization of the practical
You will see different icons through the document, the meaning of which is:
: additional or useful
information
: a worked example
: a practical exercise
: a space to answer the exercise
: a hint to solve an exercise
: a more challenging exercise
Simple versions
Plot 1
# Data set used: diamonds
p1_simple <- ggplot(diamonds, aes(clarity, log10(carat))) +
geom_point(aes(colour = cut), position = "jitter", alpha = 0.5) +
geom_violin(aes(group = clarity), fill = "black")
p1_simplePlot 2
# Data set used: mpg
p2_simple <- ggplot(mpg, aes(manufacturer, fill = class)) +
geom_bar() +
geom_text(aes(label = after_stat(count)), stat = "count", position = position_stack(vjust = 0.5))
p2_simpleNeed help with the count numbers shown in each stacked bar? https://stackoverflow.com/questions/6644997/showing-data-values-on-stacked-bar-chart-in-ggplot2
Complex versions
Plot 1
p1_complete <- p1_simple +
theme_bw() +
facet_grid(. ~ cut) +
theme(legend.position = "none") +
labs(title = "Diamond quality") +
theme(axis.text.x = element_text(angle = 45, hjust=1))
p1_completePlot 2
p2_complete <- p2_simple +
scale_fill_brewer(palette = "Dark2", name = "Car type") +
coord_flip() +
theme_minimal() +
labs(y = "Number of cars", x = "Manufacturer")
p2_complete This graph uses a
scale_fill_brewer palette, can you find which one?
Plot 3
p3_complete <- p3_simple +
theme_classic() +
scale_fill_brewer(palette = "OrRd", labels = c("Orange juice", "Vitamin C"), direction = -1) +
theme(panel.grid.major.x = element_blank()) +
labs(x = "Dose (mg/day)", y = "Tooth length", fill = "Supplement")
p3_complete This graph uses a
scale_fill_brewer palette, can you find which one?
