如何才能一(容易)共创美好x轴蜱(即PI / 2,PI,3PI / 2,...)在GGPLOT2?

问题描述 投票:4回答:3

我想创建的曲线图,其中,一个可以看到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)

... 导致 ...

是任何人都知道的更简单的方法,其中,一个可以改变一些GGPLOT2 x轴标记的基础的,例如喜欢这里的小数到pi的倍数?是否有任何漂亮的包,我错过了那么远吗?我发现这个问题有些重复,但只有在其他语言...

r ggplot2
3个回答
4
投票

这里是使分数标签的函数(也许有点麻烦)。它采用fractionsMASS包,允许您更改要在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")

## Make the graph with e axis, for example
e <- exp(1)
fracAx(p, "e")

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


5
投票

您正在寻找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)


1
投票

基于这里其他的答案我能拼凑它实现一个可独立使用的摆弄radians对象的内部一般ggplot2格式的某些功能。

numerator <- function(x) {
  f = attr(x, "fracs")
  s <- as.integer(sign(x))
  ifelse(is.finite(x), as.integer(stringr::str_extract(f, "^[^/]*")), s)
}

denominator <- function(x) {
  f = attr(x, "fracs")
  s <- as.integer(sign(x))
  ratio <- str_detect(f, "/")
  d <- as.integer(stringr::str_extract(f, "[^/]*$"))
  ifelse(is.finite(x), ifelse(ratio, d, 1L), 0L)
}

char_sign <- function(x) {
  s <- sign(x)
  ifelse(s == 1, "+",
         ifelse(s == -1, "-", ""))
}

#' Convert value to radians formatting
radians <- function(x) {
  y = x/pi
  f = suppressWarnings(MASS::as.fractions(y))
  n = suppressWarnings(numerator(f))
  d = suppressWarnings(denominator(f))
  s <- char_sign(x)
  o <- vector(mode = "character", length = length(x))
  o <- ifelse(d == 0 & n != 0, paste0(s, "∞"), o)
  o <- ifelse(n == 0 & d != 0, "0", o)
  o <- ifelse(n != 0 & d != 0, paste0(n, "π/", d), o)
  o <- ifelse(n == 1 & d != 0, paste0("π/", d), o)
  o <- ifelse(n == -1 & d == 1, paste0(s, "π"), o)
  o <- ifelse(n == -1 & d != 0 & d != 1, paste0(s, "π/", d), o)
  o <- ifelse(d == 1 & n != 0 & abs(n) != 1, paste0(n, "π"), o)
  o <- ifelse(n == d & is.finite(n), "π", o)
  o
}

这是在使用中:


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

ggplot(df, aes(time, signal)) +
  geom_line() +
  scale_x_continuous(labels = trans_format(radians, force),
                     breaks = seq(0, 4*pi, pi/2))

output of radians formatting on sine function

© www.soinside.com 2019 - 2024. All rights reserved.