va_resc | R Documentation |
2軸グラフを描く時は左軸に値をスケーリングし, 右軸は目盛り数値を調整する.
va_resc(
v,
lh_lim = NULL,
rh_lim = NULL,
scale_which = c("var", "axis"),
return_lims = FALSE
)
v |
Values to plot. 描画したい数値のベクトル. |
lh_lim |
Limit(s) of 1st (left-hand) y-axis. 左軸の範囲 (要素数2) またはvector (要素数3以上). vectorを指定した場合は range(lh_lim) となる. また, 正数であれば最大値, 負数であれば最小値のみの指定も可能 (もう一方の値は0となる). NULLの場合は range(v, na.rm = TRUE) となる. Default: NULL |
rh_lim |
Limit(s) of 2nd (right-hand) y-axis. 右軸の範囲 (要素数2) またはvector (要素数3以上). vectorを指定した場合は range(rh_lim) となる. また, 正数であれば最大値のみの指定も可能 (最小値は0となる). NULLの場合は range(v, na.rm = TRUE) となる. Default: NULL |
scale_which |
One of the following:
|
return_lims |
Logical. 変換後の数値の代わりに範囲を出力する (matrix型), Default: FALSE |
See example and also vignette("va_resc")
変換後の数値
https://blog.statsbeginner.net/entry/2020/09/08/181536
if(interactive()){
library(dplyr)
library(tidyr)
library(ggplot2)
library(patchwork)
lh <- range(faithful$waiting)
rh <- range(faithful$eruptions)
g <- faithful %>%
tidyr::pivot_longer(cols = dplyr::everything()) %>%
dplyr::mutate(val = ifelse(name == "eruptions",
va_resc(value, lh, rh, "var"), value)) %>%
ggplot(aes(x = as.integer(rownames(.)), group = name)) +
geom_line(aes(y = val, color = name), size = 0.3)
# basically
g1 <- g +
scale_y_continuous(name = "waiting", # title of left y-axis
sec.axis = sec_axis(~ va_resc(., lh, rh, "axis"),
name = "eruptions")) +
ggtitle("g1")
# a function factory is useful
create_right_axis_rescaler <- function(lh, rh) {
function(x) va_resc(x, lh_lim = lh, rh_lim = rh, "axis")
}
axis_for_eruptions <- create_right_axis_rescaler(lh = lh, rh = rh)
g2 <- g +
scale_y_continuous(name = "waiting", # title of left y-axis
sec.axis = sec_axis(~ axis_for_eruptions(.),
name = "eruptions")) +
ggtitle("g2")
# patchwork
g1 / g2
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.