我想创建一个绘图,其中可以看到x轴的替代滴答,例如pi/2,pi,3pi/2等.到目前为止,这对我来说只适用于一个相当不方便的代码(看看在那里我创建的线条pi.halfs,pi.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)
Run Code Online (Sandbox Code Playgroud)
... 导致 ...

是否有人知道一种更简单的方法,可以在ggplot2中更改某些x轴标记的基础,例如像这里从小数到pi的倍数?到目前为止我有没有错过的套餐?我发现了这个问题的一些重复,但仅限于其他语言......
您正在寻找缩放包,它允许您为缩放创建任意格式化功能,并且还内置了许多有用的格式化功能.通过缩放包帮助,我很惊讶没有找到弧度,但你应该能够创建一个使用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)
Run Code Online (Sandbox Code Playgroud)

这是一个制作分数标签的函数(可能有点笨拙)。它使用包fractions中的MASS内容并允许您更改要在 x 轴上使用的乘数。您只需向其传递一个符号(即“pi”)。如果符号有值,则刻度将按宽度*值缩放,否则仅按宽度缩放。
# Now plot the signal with the new x axis labels
p <- ggplot(data = df, aes(x = time, y = signal)) +
geom_line()
## Convert x-ticks to fractional x-ticks with a symbol multiplier
fracAx <- function(p, symbol, width=0.5) {
require(MASS) # for fractions
val <- tryCatch(eval(parse(text=symbol)), error=function(e) 1)
info <- ggplot_build(p)
xrange <- info[[2]]$ranges[[1]]$x.range/val # get the x-range of figure
vec.breaks <- seq(floor(xrange[1]), ceiling(xrange[2]), by=width)
fracs <- strsplit(attr(fractions(vec.breaks), "fracs"), "/") # convert to fractions
labels <- sapply(fracs, function(i)
if (length(i) > 1) { paste(i[1], "*", symbol, "/", i[2]) }
else { paste(i, "*", symbol) })
p + scale_x_continuous(breaks=vec.breaks*val, labels=parse(text=labels))
}
## Make the graph with pi axis
fracAx(p, "pi")
Run Code Online (Sandbox Code Playgroud)

## Make the graph with e axis, for example
e <- exp(1)
fracAx(p, "e")
Run Code Online (Sandbox Code Playgroud)

## Make the graph with a symbol that has no value
fracAx(p, "theta", width=2)
Run Code Online (Sandbox Code Playgroud)
