如何格式化2 ^ x格式的x轴刻度标签?

时间:2017-12-19 02:14:14

标签: r ggplot2

当x是log2-scale时,如何以2 ^ x格式修改x轴标签?

当它出现在图表上时,x应该最好是上标。

1 个答案:

答案 0 :(得分:8)

这是一种自定义转换和标注功能的方法。它应该适用于任意数据。

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

根据alistaire的评论,我们还可以使用scales包提供的功能格式化轴标签:

library(scales)

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

此处,trans_format将在指定转换后格式化标签。

根据手册:

  

反式
  变换对象的名称或对象   本身。内置转换包括“asn”,“atanh”,“boxcox”,   “exp”,“identity”,“log”,“log10”,“log1p”,“log2”,“logit”,   “概率”,“概率”,“互惠”,“反向”和“平方”。

     

一个   变换对象将变换捆绑在一起,它是反向的,和   生成中断和标签的方法。转换对象是   在scale包中定义,并称为name_trans,例如   boxcox_trans。您可以使用trans_new创建自己的转换。

trans应该是转化对象(比如调用scales::log2_trans的返回值)或内置转换的名称,因此我们也可以使用trans = scales::log2_trans()代替{ {1}}。

相关问题