The clarity of a plot sometimes relies on proper scaling of the axes. Very often, the scale is linear; ggplot()
displays that by default. But your data might be represented in a more meaningful way if the Y-axis is set to logarithmic, for example.
In ggplot, the scale can be set to log10
, log2
, sqrt
(square root), and reverse
(to invert the axis). Here we will see how to do this using a simple example.
Let’s start with the code for a reference plot. This plot is stored in the object baseplot
so that we can reuse it throughout the whole tutorial:
baseplot <- ggplot(df, aes(values1, values2)) +
geom_point(size=2)
baseplot
Here, we use scale_y_continuous()
to transform the Y-axis along with the argument trans = "log10"
to set the log10 scale:
baseplot +
scale_y_continuous(trans = "log10")
Use scale_y_continuous()
with trans = "log2"
to set the log2 scale:
baseplot +
scale_y_continuous(trans = "log2")
Use scale_y_continuous()
with trans = "sqrt"
to set the square root axis scale:
baseplot +
scale_y_continuous(trans = "sqrt")
Use scale_y_continuous()
with trans = "reverse"
to invert the Y-axis scale:
baseplot +
scale_y_continuous(trans = "reverse")