As mentioned before, one of the big advantages of ggplot2
is that you can change nearly all elements according your individual needs. In the following section, we will show you some ways to customize your visualizations.
A very handy feature of ggplot2
is the way you can subset data. Just add a subset function call to your graph to just visualize certain values. The subset you want to visualize can be set for all geoms
:
ggplot(iris) %+% subset(iris,Species == "setosa") + geom_point(aes(Sepal.Length, Sepal.Width))
Otherwise, you can set it for one geom
in your graph:
ggplot(iris,aes(x = Sepal.Length,y = Sepal.Width,color = Species)) + geom_point(data = subset(iris, Species %in% c("setosa","virginica")))
In ggplot2
it is very easy to add titles to graphs. Therefore, it provides the ggtitle
function. You can just add it to your graph with the plus (+
) operator:
d <- ggplot(iris, aes(Species, Sepal.Length, fill = Species)) + geom_bar(stat = "identity") d + ggtitle("Iris data: Species vs Sepal Length")
Changing the axis labels is as easy as adding a title, because ggplot
offers the scale_x_continuous
and scale_y_continuous
functions. These functions can be used to change all the settings related to the axis. You can, for example, change the title with the following:
d <- ggplot(iris ) + geom_point(aes(Sepal.Length, Sepal.Width,color = Species, shape= Species)) d + scale_x_continuous("Sepal Length") + scale_y_continuous("Sepal Width")
ggplot2
also offers a great and very easy way to swap the X and Y axes of your graph. You just have to add the coord_flip()
function to your graph:
d + coord_flip()
ggplot2
offers, with its themes option, a great way to make your visualizations look much better and stand out against nearly every graph created with base plotting. In addition to this, there is a very interesting package by Jeffrey B. Arnold with the name, ggthemes. This package adds a whole bunch of extra options to the existing themes and scales of ggplot2
. It includes, for example, a theme based on the design of the Economist, or one based on the Wall Street Journal's design.
Through the following code, we will show you how to make this graph look even better:
d <- ggplot(iris, aes(Sepal.Length, Sepal.Width, colour = Species)) + geom_point()
Install and load the
ggthemes
package with the following lines:
install.packages("ggthemes") library(ggthemes)
We can then add a new theme to our ggplot
object, d
. For this, we will use the theme_economist()
and scale_color_economist()
functions from the ggthemes
package. The first adapts the graph background to the economist background, and the second one the scale:
d + theme_economist() + scale_color_economist() + ggtitle("Iris Species: Sepal Length vs Sepal Width)