gpt4 book ai didi

r - 如何以 sqrt(x) 格式格式化 x 轴刻度标签?

转载 作者:行者123 更新时间:2023-12-05 04:06:07 27 4
gpt4 key购买 nike

我在研究ggplot2的coord_trans()的例子:

library(ggplot2)
library(scales)

set.seed(4747)

df <- data.frame(a = abs(rnorm(26)),letters)
plot <- ggplot(df,aes(a,letters)) + geom_point()
plot + coord_trans(x = "log10")
plot + coord_trans(x = "sqrt")

我修改了代码 plot + coord_trans(x = "log10") 如下,得到了我预期的结果:

plot + scale_x_log10(breaks=trans_breaks("log10", function(x) 10^x),
labels=trans_format("log10", math_format(10^.x)))

我修改了代码 plot + coord_trans(x = "sqrt") 如下,得到了一个奇怪的 x 轴:

plot + scale_x_sqrt(breaks=trans_breaks("sqrt", function(x) sqrt(x)),
labels=trans_format("sqrt", math_format(.x^0.5)))

我该如何解决这个问题?

最佳答案

我明白你为什么说这是一个奇怪/可怕的轴。 trans_breaks 的文档甚至在第一行就此警告您:

These often do not produce very attractive breaks.

为了减少它的吸引力,我会使用 round(,2) 这样我的轴标签只有 2 个小数点而不是默认的 8 或 9 - 使轴变得困惑。然后我会设置一个合理的范围,在你的情况下说 0 到 5 (c(0,5))。

最后,您可以在 trans_breaks 调用中使用 n 指定坐标轴的刻度数。

所以把它们放在一起,下面是如何以 scale_x_sqrt(x) 格式设置 x 轴及其刻度标签的格式:

plot <- ggplot(df,aes(a,letters)) + geom_point()
plot + scale_x_sqrt(breaks=trans_breaks("sqrt", function(x) round(sqrt(x),2), n=5)(c(0, 5)))

产生这个: enter image description here

c(0,5) 被传递给 pretty(),这是一个鲜为人知的 Base R 函数。根据文档,pretty 执行以下操作:

Compute a sequence of about n+1 equally spaced "round" values which cover the range of the values in x.

pretty(c(0,5)) 在我们的例子中只是生成 [1] 0 1 2 3 4 5

您甚至可以通过更改参数来微调轴。这里的代码使用 3 个小数点 (round(x,3)),我们要求 3 个刻度 n=3:

plot <- ggplot(df,aes(a,letters)) + geom_point()
plot + scale_x_sqrt(breaks=trans_breaks("sqrt", function(x) round(sqrt(x),3), n=3)(c(0, 5)))

产生这个: enter image description here

EDIT 根据 OP 的附加评论:要获取整数值,floor()round(x,0) 有效,因此以下代码:

plot <- ggplot(df,aes(a,letters)) + geom_point()
plot + scale_x_sqrt(breaks=trans_breaks("sqrt", function(x) round(sqrt(x),0), n=5)(c(0, 5)))

产生这个: enter image description here

关于r - 如何以 sqrt(x) 格式格式化 x 轴刻度标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50229191/

27 4 0