0

I am trying to assign names to the Class by which facet_grid() splits the plot using the "labeller =" argument but it is ignored when I am using it in a particular dataset. The syntax works though with the following reproducible example using mtcars dataset from base R:

    labels <- c( "1" = "One", "0" = "Zero")
ggplot(mtcars, aes(x = hp) )+
  geom_histogram(aes(y=..density..), position="identity",alpha = 0.8, fill = "red") +
  ggtitle("hp histogram)") + 
  xlab("Hp") +  theme_economist()  + facet_grid( am ~ .,  labeller=labeller(am = labels)) +
  theme(strip.text.y = element_text(size=12, face="bold", colour = "white"),
        strip.background = element_rect(fill="cornflowerblue"))

enter image description here

When I use the same syntax though with the german credit dataset (can be found in the UCI Machine Learning Repository) the argument is ignored:

labels <- c( "1" = "Bad Credit", "0" = "Good Credit")


plot_data <- german_fct_train %>% group_by(Class,F_Savings_account_bonds  ) %>% summarise(count = n())
plot_data <- plot_data %>% group_by(Class) %>% mutate(freq = count/sum(count))

ggplot(plot_data, aes(x = F_Savings_account_bonds, y = freq ) )+
  geom_bar(stat="identity", alpha = 0.8, fill = "red") +
  ggtitle("Savings/Bonds Account \n (Bad Credit = 1, Good Credit = 0)") + 
  theme_economist()  + 
  scale_x_discrete(name = "Status of Savings/Bonds Account") + 
  scale_y_continuous(name = "Relative Frequency" , labels = percent, breaks = seq(0, 0.8, 0.1)) +
  facet_grid( as.factor(Class) ~ . , labeller=labeller(Class = labels)) +
  theme(strip.text.y = element_text(size=12, face="bold", colour = "white"),
        strip.background = element_rect(fill="cornflowerblue")) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

enter image description here

Your advice will be appreciated.

rf7
  • 1,993
  • 4
  • 21
  • 35
  • Please read [How to make a great reproducible example in R?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) You should make a minimal example of your data set. Do not point us to an external source for the data. You should include what libraries you used. Basically read that link and edit your question accordingly. – M-- Jul 21 '17 at 20:33
  • 1
    This is because you are using `as.factor` around your variable in `facet_grid` but not within `labeller`. It's unnecessary to `as.factor` here, but if you keep using it you'll need `as.factor(Class)` in `labeller`. This will only work if wrapped in back-ticks: ```labeller(`as.factor(Class)` = labels)``` – aosmith Jul 21 '17 at 20:59

0 Answers0