How could I use a variable create in 'mutate' as label in 'scale_y_discrete'?

Hi Dears,

How could I use a variable create in the mutate function as label in the scale_y_discrete in the same chunk of code?

Here is a example code:

diamonds %>% 
  group_by(cut) %>% 
  summarise(avg = mean(price)) %>% 
  ungroup() %>% 
  mutate(fake.label = paste0("fake", cut)) %>% 
  mutate(cut = fct_reorder(cut, avg)) %>% 
  ggplot(aes(y = cut, x = avg))+
  geom_col()+
  scale_y_discrete()

First, I tried something like scale_y_discrete(aes(labels = fake.label). Did not work. After, I've tried create a function like:

label.f <- function(cut) {
    paste0("fake", cut)
}

And then, tried to use in like this:

diamonds %>% 
  group_by(cut) %>% 
  summarise(avg = mean(price)) %>% 
  ungroup() %>% 
  #mutate(fake.label = paste0("fake", cut)) %>% 
  mutate(cut = fct_reorder(cut, avg)) %>% 
  ggplot(aes(y = cut, x = avg, labels = fake.label))+
  geom_col()+
 scale_y_discrete(labels = label.f(cut))

I've got an error that I don't understand.

Could someone help me, please. Thanks in advantage.

Try this workaround

library(forcats)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

diamonds2 <- diamonds %>% 
  group_by(cut) %>% 
  summarise(avg = mean(price)) %>% 
  ungroup() %>% 
  mutate(fake.label = paste0("fake", cut)) %>% 
  mutate(cut = fct_reorder(cut, avg)) 

diamonds2 %>% 
  ggplot(aes(y = cut, x = avg))+
  geom_col()+
  scale_y_discrete(labels = diamonds2$fake.label) +
  theme_minimal()

1 Like

Thank you. But, in this way the order of the labels has changed. If I take-off the argument labels = diamonds2$fake.label, the order of the labels are different:

diamonds2 %>%
ggplot(aes(y = cut, x = avg))+
geom_col()+
scale_y_discrete() +
theme_minimal()

Or have I missing something?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.