The coordinate system adjusts the mapping from coordinates to the 2D plane of the computer screen. Among the different coordinate systems available in ggplot2
, the Cartesian system is the most common coordinate system for two dimensions, while the polar coordinate system is often used for special plots, such as pie charts. When you create a plot, the coordinate system for the graph will be set with default values, which, in most cases, would be Cartesian coordinates. If you want a different coordinate system, you can overwrite the default value using the appropriate function. Such functions have the general form coord_x
, where x is replaced by the specific coordinate desired.
The following is a table summarizing the main functions of coordinate systems; a more exhaustive list can be found on the package website:
We will now see a couple of examples of how to use a few of these functions. We will first have a look at the coord_flip()
function which simply changes the axes of the plot. In most cases, you will not need any additional argument, so for instance, if we consider the plot in Figure 2.14, representing the data from the ToothGrowth
dataset, we have already seen in the previous section how we can obtain the same plot defining the different layers with ggplot()
. If now, we want to flip the coordinates, we simply need to change the coordinate system. The following code shows this:
ggplot(data=ToothGrowth, aes(x=dose, y=len, col=supp)) + geom_point() + coord_flip()
This code will create the plot in Figure 3.5, where the x and y axes are flipped compared to the default coordinates:
One other very useful function is the coord_fixed()
function which allows us to create a plot with a fixed ratio of the y and x axes. The default value for the ratio argument is 1 which creates a plot with the same fixed axis extension for x and y, ensuring that one unit on the x axis is the same length as one unit on the y axis. Just remember that this does not mean that the two axes will have the same range but simply that the unit extension would be the same.
So, for instance, if we take the plot in our previous example, we could, instead of flipping the coordinates, set them to a fixed value. The following code shows this:
ggplot(data=ToothGrowth, aes(x=dose, y=len, col=supp)) + geom_point() + coord_fixed(ratio=0.1)
In this case, we have fixed the ratio of the two axes to 0.1
, meaning that one length unit on the x axis will be translated to 10 units on the y axis. The plot generated with the previous code is represented in Figure 3.6: