ggplot2 scale_x_log10() in R: Log-Transform the X Axis
The scale_x_log10() function in ggplot2 is a shortcut to log10-transform the X axis. It is essential for visualizing wide-range or skewed data where small and large values must coexist on one plot.
+ scale_x_log10()
+ scale_x_log10(labels = scales::comma)
+ scale_x_log10(breaks = c(1, 10, 100, 1000))
+ scale_x_continuous(trans = "log10") # equivalent
+ scale_x_log10(labels = scales::label_log())Need explanation? Read on for examples and pitfalls.
What scale_x_log10() does in one sentence
scale_x_log10() log10-transforms the X axis values, equivalent to scale_x_continuous(trans = "log10") but shorter. Useful for skewed positive data spanning multiple orders of magnitude.
Syntax
scale_x_log10(name = waiver(), breaks = waiver(), labels = waiver(), ...). Same arguments as scale_x_continuous.
Five common patterns
1. Standard log x
2. Comma-formatted log labels
3. Custom breaks
4. Scientific notation labels
5. Both axes log
scale_x_log10() vs scale_x_continuous(trans=) vs scale_x_sqrt
| Function | Transform |
|---|---|
scale_x_log10() |
Log base 10 (shortcut) |
scale_x_continuous(trans = "log10") |
Same; explicit |
scale_x_continuous(trans = "log") |
Natural log |
scale_x_sqrt() |
Square root |
scale_x_continuous(trans = "log2") |
Log base 2 |
A practical workflow
For skewed data (revenue, GDP, population, etc.), log scales are the default visualization choice.
Both axes log; comma + dollar formatting.
Common pitfalls
Pitfall 1: zero or negative values. Log fails for non-positive numbers. Filter or shift before plotting.
Pitfall 2: misleading interpretation. Linear-looking trends on log axes are EXPONENTIAL in raw data. Always disclose log scales in titles or captions.
scale_x_log10() may produce unexpected breaks. For control, set breaks = c(1, 10, 100, ...) explicitly.Try it yourself
Try it: Plot mtcars hp on log10 x with comma-formatted labels. Save to ex_plot.
Click to reveal solution
Explanation: Log10 x-axis with comma labels.
Related ggplot2 functions
After mastering scale_x_log10, look at:
scale_y_log10(): log y axisscale_x_sqrt(): square root xscale_x_continuous(trans = ...): arbitrary transformationscoord_trans(x = "log10"): visual-only transform (no stat impact)scales::label_log()/comma: label formatters
FAQ
What does scale_x_log10 do in ggplot2?
scale_x_log10() log10-transforms the X axis. Shortcut for scale_x_continuous(trans = "log10").
How do I add comma labels to log x?
scale_x_log10(labels = scales::comma).
Can I use log10 with negative numbers?
No. Log fails on zero and negative values; ggplot drops those points with a warning.
What is the difference between scale_x_log10 and coord_trans(x = "log10")?
scale_x_log10 transforms the data BEFORE stats run (e.g., regression line is fit on log values). coord_trans transforms only the VISUAL after stats run.
How do I get powers-of-10 axis labels?
scale_x_log10(labels = scales::label_log()) produces 10^N format.