gpt4 book ai didi

r - 如何将 x 轴刻度标签格式化为 2^x 格式?

转载 作者:行者123 更新时间:2023-12-02 07:33:04 25 4
gpt4 key购买 nike

当 x 为 log2 刻度时,如何修改 2^x 格式的 x 轴标签?

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

最佳答案

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

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

<小时/>

根据alisaire的评论,我们还可以使用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将在指定转换后格式化标签。

<小时/>

根据手册:

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 应该是一个转换对象(如调用 scales::log2_trans 的返回值)或内置转换的名称,因此我们也可以使用 trans = scales::log2_trans() 而不是 trans = 'log2'

关于r - 如何将 x 轴刻度标签格式化为 2^x 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com