0
votes

I am creating a box plot in which I have used scale_x_reordered() after adjusting the order of factors on the x axis.

I am now trying to change the label of one factor. I had previously been doing this using:

scale_x_discrete(labels=c("old_label" = "new_label"))

However, I cannot use both scale_x_discrete() and scale_x_reordered() in the same plot. Does anyone know of a fix so that I can change a label and keep scale_x_reordered?

My ggplot is based off of this very helpful example: linked here

The change I am trying to make is equivalent to manually changing the name "Michael" to "Mike".

1
Try giving labels=c("old_label" = "new_label") as an argument to scale_x_reorderedGregor Thomas
Yes, I've tried that. I get the error message: "Error in discrete_scale(c("x", "xmin", "xmax", "xend"), "position_d", : formal argument "labels" matched by multiple actual arguments"eycramer
It would be easier to help if you create a small reproducible example along with expected output. Read about how to give a reproducible example.Ronak Shah

1 Answers

1
votes

To achieve your desired result I would suggest to recode your factor before applying reorder_within.

The reason is that reorder_within transforms the factor levels to make the reordering within facets work. Inside scale_x_reordered a re-transformation is applied via the labels argument to show the original levels or labels. That's why you can't make use of the labels argument.

In the following example taken from the link you posted I make use of dplyr::recode(name, "Michael" = "Mike") just before reorder_within:

library(tidyverse)
library(babynames)
library(tidytext)

top_names <- babynames %>%
  filter(year >= 1950,
         year < 1990) %>%
  mutate(decade = (year %/% 10) * 10) %>%
  group_by(decade) %>%
  count(name, wt = n, sort = TRUE) %>%
  ungroup

top_names %>%
  group_by(decade) %>%
  top_n(15) %>%
  ungroup %>%
  mutate(decade = as.factor(decade),
         name = recode(name, "Michael" = "Mike"),
         name = reorder_within(name, n, decade)) %>%
  ggplot(aes(name, n, fill = decade)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(~decade, scales = "free_y") +
  coord_flip() +
  scale_x_reordered() +
  scale_y_continuous(expand = c(0,0)) +
  labs(y = "Number of babies per decade",
       x = NULL,
       title = "What were the most common baby names in each decade?",
       subtitle = "Via US Social Security Administration")
#> Selecting by n