juliasilge / tidytext

Text mining using tidy tools :sparkles::page_facing_up::sparkles:

Home Page:https://juliasilge.github.io/tidytext/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

scales::wrap_format() does not work with scale_*_reordered

ariespirgel opened this issue · comments

Thank you for the great function reorder_within. I am not sure if this is a {scales} issue or a {tidytext} issue, but it seems like scales::wrap_format() does not work with scale_*_reordered. For example:

library(tidyverse)
library(tidytext)
library(scales)
#> 
#> Attaching package: 'scales'
#> The following object is masked from 'package:purrr':
#> 
#>     discard
#> The following object is masked from 'package:readr':
#> 
#>     col_factor

diamonds %>% 
  group_by(cut, color) %>% 
  summarise(mean_price = mean(price)) %>% 
  ungroup() %>% 
  mutate(cut = reorder_within(cut, mean_price, color)) %>% 
  ggplot(aes(x = cut, y = mean_price)) +
  geom_col() +
  facet_wrap(~color, scales = "free_x") +
  scale_x_reordered(label = wrap_format(3))
#> `summarise()` has grouped output by 'cut'. You can override using the `.groups`
#> argument.
#> Error in discrete_scale(c("x", "xmin", "xmax", "xend"), "position_d", : unused argument (label = function (x) 
#> {
#>     unlist(lapply(strwrap(x, width = width, simplify = FALSE), paste0, collapse = "\n"))
#> })

Changing scale_x_reordered to scale_x_discrete does not produce an error, but then you get the reorder_within appended variable names. Thank you for your time.

I think a couple of things are tripping you up here.

  • The first is that the argument to the scale_*() functions is labels, not label. (Looks like partial matching has come to trouble you.)
  • The second is that you need to pass a function to labels that knows what to do when you are using reorder_within(). The function scales::label_wrap() doesn't know what to do in this special case.

This example gets around both issues:

library(tidyverse)
library(tidytext)
library(stringr)

custom_labeler <- function(x) {
    x %>%
        str_replace("___.+$", "") %>%
        str_wrap(width = 3)
}

diamonds %>% 
    group_by(cut, color) %>% 
    summarise(mean_price = mean(price)) %>% 
    ungroup() %>% 
    mutate(cut = reorder_within(cut, mean_price, color)) %>% 
    ggplot(aes(x = cut, y = mean_price)) +
    geom_col() +
    facet_wrap(~color, scales = "free_x") +
    scale_x_reordered(labels = custom_labeler)
#> `summarise()` has grouped output by 'cut'. You can override using the `.groups`
#> argument.

Created on 2022-10-04 with reprex v2.0.2

That gets the job done. Thank you for your quick response and for all of your contributions to the open-source community.

You are so welcome!

This issue has been automatically locked. If you believe you have found a related problem, please file a new issue (with a reprex: https://reprex.tidyverse.org) and link to this issue.