通过scales::number()修改轴标签时,将结合使用NA和facetted_pos_scales()

egdjgwm8  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(88)

由于ggh4x包,我有了下面的蝴蝶图,它可以按预期工作。

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))))

当我尝试通过labels = scales::label_number(decimal.mark = ",") NAs修改左x轴标签时,会引入。

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))))

当我对右轴进行同样的尝试时,问题没有出现。(我使用label_percent()是因为右轴上没有小数点可以更改。但类似地,label_percent()在左轴上也不起作用。

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())))

这里的问题是什么,我如何解决它?

uujelgoq

uujelgoq1#

该问题与ggh4x::facetted_pos_scales无关,而是由于根据文档设置reverse_num=TRUE所致
会将该面板的轴标签乘以-1。
我还没有仔细看过,但我猜这个乘法是在格式化标签上完成的,因此会产生NA。
要修复该集合reverse_num=FALSE并在应用scales::label_number之前转换mnumeric,例如通过使用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))

相关问题