What does it mean (.) in R? As in
sec_axis(~ log(2)/(.),
breaks = c(2:7,14,21),
name = "Doubling time (days)")
)
Besides, it gives an error. The error message is Error: transformation for secondary axes must be monotonic
Thanks!
What does it mean (.) in R? As in
sec_axis(~ log(2)/(.),
breaks = c(2:7,14,21),
name = "Doubling time (days)")
)
Besides, it gives an error. The error message is Error: transformation for secondary axes must be monotonic
Thanks!
To give out a proper answer, you should post a reproducible example: data + the ggplot code.
If sec_axis()
is inside scale_y_continuous
, the .
is the place holder for the values shown on the main Y axis [if it's in scale_x_continuous
, it's the place holder for the values shown on the main X axis.].
About the error, I wasn't able to reproduce it. You need to share your ggplot code (a minimal reproducible example that shows the error) and the version you have of ggplot2
.
EDIT:
I managed to reproduce the error.
set.seed(1)
df <- data.frame(x = 1:100, y = rnorm(100))
# works!
ggplot(df) +
geom_line(aes(x = x, y = y))
# doesn't work
ggplot(df) +
geom_line(aes(x = x, y = y)) +
scale_y_continuous(sec.axis = sec_axis(trans = ~1/.))
#> Errore: transformation for secondary axes must be monotonic
That happens because zero belongs to the Y axis. In R if you try to divide by zero, it will return Inf, which can't be plotted in an axis. Therefore, the error.
The only way to avoid it is a trick: change the labels and the breaks, without actually applying any transformation. As the example below (obviously this example is meaningless):
ggplot(df) +
geom_line(aes(x = x, y = y)) +
scale_y_continuous(sec.axis = sec_axis(~., label = c(-10:-1, 1:10), breaks = 1/c(-10:-1, 1:10)))
In order to reproduce Professor Hyndman's chart, you should do as follow:
library(tidyverse)
library(tsibble)
library(tidycovid19) #remotes::install_github("joachim-gassen/tidycovid19")
updates <- download_merged_data(cached = TRUE)
updates %>%
mutate(
cases_logratio = difference(log(confirmed))
) %>%
filter(iso3c %in% countries) %>%
filter(date >= as.Date("2020-03-01")) %>%
ggplot(aes(x = date, y = cases_logratio, col = country)) +
geom_hline(yintercept = log(2)/c(2:7,14,21), col='grey') +
geom_smooth(method = "loess", se = FALSE) +
scale_y_continuous(
"Daily increase in cumulative cases",
breaks = log(1+seq(0,60,by=10)/100),
labels = paste0(seq(0,60,by=10),"%"),
minor_breaks=NULL,
sec.axis = sec_axis(~ .,
labels = c(2:7,14,21),
breaks = log(2)/c(2:7,14,21),
name = "Doubling time (days)")
) +
ggthemes::scale_color_colorblind()