Changing axes appearance to ggplot2 plot (continous axes)

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:

  • Iris setosa
  • Iris virginica
  • Iris versicolor

On each sample for features were recorded:

  • length of the sepals
  • width of the sepals
  • length of the petals
  • width of the petals

For a general and brief introduction to ggplot plots, take a look at the How it works… section of the previous recipe.

Getting ready

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()  
Getting ready

How to do it...

  1. Set axis range from 0 to 10.

    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.

    .

    How to do it...

    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:

    How to do it...
  2. Hide the tick marks:
    plot <- plot + scale_y_continuous(breaks = NULL) + scale_x_continuous(breaks = NULL)
    How to do it...
  3. Set a fixed ratio between x and y axes:
    plot <- plot + coord_fixed(ratio = 4/3)
    How to do it...

It feels like some kind of pop art, doesn't it?

So, you are now a ggplot artist, congratulations!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset