This recipe shows you how to get control over an axis within a ggplot plot.
The ggplot2
package does a great job of automatically setting the appearance of the axes, but sometimes, even in the early stages of your project, you may want your axis to appear in a specific shape, showing, for instance, a defined number of tickmarks.
This is what this recipe is all about—giving you control over the appearance of your ggplot
axes.
In this example, we will use a plot based on the Iris dataset.
The Iris dataset is one of most used datasets in R tutorials and learning sessions, and it is derived from a 1936 paper by Ronald Fisher, named The use of multiple measurements in taxonomic problems.
Data was observed on 50 samples of three species of the iris flower:
On each sample for features were recorded:
For a general and brief introduction to ggplot
plots, take a look at the How it works… section of the previous recipe.
The first step needed to get started with this recipe is ggplot2
package installation and loading:
install.packages("ggplot2") library(ggplot2)
After doing that, we will be able to create a ggplot2
plot to work on in this recipe:
plot <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point()
Using the expand_limits()
function, we can set the origin and the end of the x and y axes, passing these values in two different vectors, one for the x and one for the y argument of the expand_limits()
function:
plot <- plot + expand_limits(x = c(0,10),y = c(0,10))
This will result in setting the range of the x and y axes from 0 to 10.
.
By displaying predetermined tick marks, ggplot
automatically defines a convenient number of tick marks, working this out with its own internal algorithms. However, you can force the plot to have a custom number of algorithms using the scale_y_continuos()
and scale_x_continuos()
functions, passing a vector with the desired breaks to the breaks
argument:
plot <- plot + scale_y_continuous(breaks = c(0,5,10))
This piece of code, for instance, will result in a plot having tick marks only on 0, 5, and 10:
plot <- plot + scale_y_continuous(breaks = NULL) + scale_x_continuous(breaks = NULL)
plot <- plot + coord_fixed(ratio = 4/3)
It feels like some kind of pop art, doesn't it?
So, you are now a ggplot
artist, congratulations!