I have the following butterfly plot that works as expected thanks to the ggh4x
package.
librarian::shelf(ggpol, tidyverse)
dat <-
tibble(group = rep(letters[1:5], each = 2),
type = factor(paste0("type", rep(c(1:2), 5))),
value = c(-50, 110, -45, 120, -40, 130, -35, 140, -30, 150))
dat %>%
ggplot(aes(x = value, y = group)) +
geom_col() +
facet_share(~type, scales = "free", reverse_num = TRUE) +
facetted_pos_scales(
x = list(scale_x_continuous(limits = c(-40, -30)),
scale_x_continuous(limits = c(35, 215))))
When I try to modify the left x axis labels via labels = scales::label_number(decimal.mark = ",")
NAs are introduced.
dat %>%
ggplot(aes(x = value, y = group)) +
geom_col() +
facet_share(~type, scales = "free", reverse_num = TRUE) +
facetted_pos_scales(
x = list(scale_x_continuous(limits = c(-40, -30),
labels = label_number(decimal.mark = ",")),
scale_x_continuous(limits = c(35, 215))))
When I try the same for the right axis, the problem does not appear. (I use label_percent()
because there are no decimal points in the right axis to change. But similarly label_percent()
would not work on the left axis.
dat %>%
ggplot(aes(x = value, y = group)) +
geom_col() +
facet_share(~type, scales = "free", reverse_num = TRUE) +
facetted_pos_scales(
x = list(scale_x_continuous(limits = c(-40, -30)),
scale_x_continuous(limits = c(35, 215),
labels = label_percent())))
What is the problem here and how can I solve it?
The issue is not related to ggh4x::facetted_pos_scales
but due to setting reverse_num=TRUE
which according to the docs
will multiply the axis labels for that panel by -1.
Haven't had a closer look but would guess that this multiplication is done on the formatted labels and hence will result in the NAs.
To fix that set reverse_num=FALSE
and transform the mnumerics before applying the scales::label_number
, e.g. by using abs()
:
library(tidyverse)
library(ggpol)
library(ggh4x)
dat <-
tibble(
group = rep(letters[1:5], each = 2),
type = factor(paste0("type", rep(c(1:2), 5))),
value = c(-50, 110, -45, 120, -40, 130, -35, 140, -30, 150)
)
dat %>%
ggplot(aes(x = value, y = group)) +
geom_col() +
facet_share(~type, scales = "free") +
facetted_pos_scales(
x = list(
scale_x_continuous(
limits = c(-40, -30),
labels = ~scales::label_number(decimal.mark = ",")(abs(.x))
),
scale_x_continuous(limits = c(35, 215))
)
) +
theme(axis.text.x = element_text(size = 20))