head(iris) ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## 1 5.1 3.5 1.4 0.2 setosa ## 2 4.9 3.0 1.4 0.2 setosa ## 3 4.7 3.2 1.3 0.2 setosa ## 4 4.6 3.1 1.5 0.2 setosa ## 5 5.0 3.6 1.4 0.2 setosa ## 6 5.4 3.9 1.7 0.4 setosa
2018-11-15
head(iris) ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## 1 5.1 3.5 1.4 0.2 setosa ## 2 4.9 3.0 1.4 0.2 setosa ## 3 4.7 3.2 1.3 0.2 setosa ## 4 4.6 3.1 1.5 0.2 setosa ## 5 5.0 3.6 1.4 0.2 setosa ## 6 5.4 3.9 1.7 0.4 setosa
Functions create graphics, example with Fisher's Iris:
hist(iris$Petal.Length, col = "grey", border = "white",
main = "Example of a histogram", xlab = "Fisher's Iris: petal length")
Functions create a graphical object:
my_plot <- ggplot(iris) + geom_histogram(aes(Petal.Length)) +
labs(title = "Example of a histogram",
x = "Fisher's Iris: petal length")
my_plot
ggplot2 builds graphics one component at a time. The grammar includes:
ggplot(): to provide the datageom_...: to define the type of graphaes(): to map features of data into aesthetic properties (e.g. shapes, colors)my_plot <- ggplot(iris) + # use 'iris' data.frame
geom_histogram(aes(Petal.Length)) + # hist using petal length
labs(title = "Example of a histogram", # add title
x = "Fisher's Iris: petal length") # add x label
For instance, to color histograms by species:
my_plot + aes(fill = Species)
my_plot <- ggplot(iris, aes(x = Petal.Length, y = Sepal.Length)) +
geom_point(aes(color = Species, shape = Species),
size = 5, alpha = .75) +
geom_smooth() +
labs(title = "Example of a scatterplot")
my_plot
Learn more about ggplot2:
geoms_ (types of plot)aes() specifications (colors / shapes / etc.)charactercol <- c(setosa = "#666699", versicolor = "#99cc00", virginica = "#b30059") my_plot + scale_color_manual(values = col)
Note that you will need to use scale_fill_manual for colors specified through fill = ....
You can use facet_grid(rows ~ columns) to specify panels:
new_plot <- ggplot(iris) + geom_histogram(aes(x = Petal.Length, fill = Species)) + scale_fill_manual(values = col) + facet_grid(Species ~ .) new_plot
Use theme(legend.position = c(x_coord, y_coord)) to move the legend:
new_plot + theme(legend.position = c(.9, .8))
Other themes are available and can be customised:
new_plot + theme_light(base_family = "Times", base_size = 20)