Tranformations in ggplot2

This is a quick summary of how transformations, applied to either the data, the scale, or the coordinate system, are reflected in a ggplot2 object.

require(ggplot2)
## Loading required package: ggplot2

# Subset diamonds for slightly more manageable dataframe:
didat <- diamonds[sample(nrow(diamonds), 500), ]

# Original data:
ggplot(didat, aes(x = depth, y = price)) + geom_point()

plot of chunk unnamed-chunk-1

There are three ways to transform the plot elements in ggplot. We can transform the data, the scales, or the coordinate system.

# Transform data:
ggplot(didat, aes(x = log10(depth), y = log10(price))) + geom_point()

plot of chunk unnamed-chunk-2


# Transform scales (same plot as transform data, but scales go wonky):
ggplot(didat, aes(x = depth, y = price)) + geom_point() + scale_x_log10() + 
    scale_y_log10()

plot of chunk unnamed-chunk-2


# Transform coordinate system:
ggplot(didat, aes(x = depth, y = price)) + geom_point() + coord_trans(x = "log10", 
    y = "log10")

plot of chunk unnamed-chunk-2