Search code examples
rggplot2facet-grid

How to change colour of histograms with facet_grid and the position of the text?


How can I change the colour for the two histograms plot made with facet_grid? I would like to have the histogram of "Active" in green and "Failed" in red.

And also, how can I change the position of the text of the line in order to have it a bit more down?

Here is my code:

df %>%
  ggplot(aes(x = `Banks/turnover%Last avail. yr`)) +
  geom_histogram(
      bins = nclass.Sturges(`Banks/turnover%Last avail. yr`),colour = "black")+
  geom_vline(data = status_means, aes(xintercept = avg),  color="red", linetype="dashed")+
  geom_text(data = status_means , aes(x = avg, label = avg), y= Inf )+
  theme(legend.position="None")+
  facet_grid(~general_status)

enter image description here


Solution

  • You need to add a factor to the fill parameter. Here, I just use active-failed as I'm not sure how you have that distinguished in your data.

    ggplot(df_all,
           aes(x = `Banks/turnover%Last avail. yr`, fill = as.factor(active-failed)))
    

    Then, you can add a line to define the colors:

    scale_fill_manual(values = c("green", "red"))
    

    As @teunbrand said, you can just use vjust to move the text so that it is not cut off.

    Remember to give a good reproducible example, it is helpful to provide some of your data via dput(head(df)).