user849204
user849204

Reputation:

How to format x-axis tick label in 2^x format?

How do I modify x-axis label in 2^x format when x is in log2-scale?

When it appears on the graph, x should be preferably in superscript.

Upvotes: 8

Views: 1096

Answers (2)

Maël
Maël

Reputation: 51994

You can use scales::label_log with base = 2:

library(ggplot2)
library(scales)

ggplot(mtcars, aes(mpg, cyl)) +
  geom_point() +
  scale_x_continuous(
    trans = "log2", 
    labels = label_log(2)
  )

enter image description here

Upvotes: 0

mt1022
mt1022

Reputation: 17289

Here is a way to do it custom transformation and labelling function. It should work on arbitrary data.

library(ggplot2)

label_log2 <- function(x) parse(text = paste0('2^', log(x, 2)))

ggplot(mtcars, aes(mpg, cyl)) +
    geom_point() +
    scale_x_continuous(
        trans = 'log2',
        labels = label_log2)

enter image description here


According to alistaire's comment, we can also format axis labels with functions provided by scales package:

library(scales)

ggplot(mtcars, aes(mpg, cyl)) +
    geom_point() +
    scale_x_continuous(
        trans = 'log2',
        labels = trans_format('log2', math_format(2^.x)))

Here, trans_format will format the labels after specified transformation.


According to manual:

trans
Either the name of a transformation object, or the object itself. Built-in transformations include "asn", "atanh", "boxcox", "exp", "identity", "log", "log10", "log1p", "log2", "logit", "probability", "probit", "reciprocal", "reverse" and "sqrt".

A transformation object bundles together a transform, it's inverse, and methods for generating breaks and labels. Transformation objects are defined in the scales package, and are called name_trans, e.g. boxcox_trans. You can create your own transformation with trans_new.

trans should be a transformation object (like the return value of a call to scales::log2_trans) or the name of built-in transformation, so we can also use trans = scales::log2_trans() instead of trans = 'log2'.

Upvotes: 8

Related Questions