gpt4 book ai didi

r - 如何(更容易)在 ggplot2 中创建漂亮的 x 轴刻度(即 pi/2, pi, 3pi/2, ...)?

转载 作者:行者123 更新时间:2023-12-04 22:45:04 29 4
gpt4 key购买 nike

我想创建一个图,在那里可以看到 x 轴的替代刻度,例如pi/2, pi, 3pi/2, 等等。到目前为止,这对我来说只适用于一个相当不方便的代码(看看我创建的行 pi.halfspi.fulls 并稍后将它们合并到 vec.expr ):

require (ggplot2)

# Create vectors: breaks and corresponding labels as multiples of pi/2
vec.breaks <- seq(from = pi/2, to = 7*pi/2, by = pi/2)
pi.halfs <- c(paste(expression(pi), "/2"),
paste(seq(from = 3, to = 21, by = 2), "*" , expression(pi), "/2"))
pi.fulls <- c(paste(expression(pi)),
paste(seq(from = 2, to = 11, by = 1), "*" , expression(pi)))
vec.expr <- parse(text = c(rbind(pi.halfs, pi.fulls)))[1:7]

# Create some time and signal
time <- seq(from = 0, to = 4*pi, by = 0.01)
signal <- sin(time)
df <- data.frame(time,signal)

# Now plot the signal with the new x axis labels
fig <- ggplot(data = df, aes(x = time, y = signal)) +
geom_line() +
scale_x_continuous(breaks=vec.breaks, labels=vec.expr)
print(fig)

... 导致 ...

output figure

有没有人知道一种更简单的方法,可以在 ggplot2 中更改某些 x 轴标签的基数,例如像这里从小数到 pi 的倍数?有没有什么好的包,我到目前为止错过了?我发现了这个问题的一些重复,但仅限于其他语言......

最佳答案

您正在寻找 scales包,它允许您为刻度创建任意格式函数,并且还内置了许多有用的格式函数。查看 scales 包帮助,我很惊讶没有找到弧度刻度,但您应该能够创建一个使用math_formatter() .这段代码得到相同的结果,但不是分数。

library(ggplot2)
library(scales)

time <- seq(from = 0, to = 4*pi, by = 0.01)
signal <- sin(time)
df <- data.frame(time,signal)

pi_scales <- math_format(.x * pi, format = function(x) x / pi)

fig <- ggplot(data = df, aes(x = time, y = signal)) +
geom_line() +
scale_x_continuous(labels = pi_scales, breaks = seq(pi / 2, 7 * pi / 2, pi / 2))

print(fig)

Plot with pi in x axis

关于r - 如何(更容易)在 ggplot2 中创建漂亮的 x 轴刻度(即 pi/2, pi, 3pi/2, ...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31187204/

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