Search code examples
rdataframeggplot2geom-bar

Cannot rotate x axis labels in ggplot2 facet graphs in r



Can anyone help out with a task?
I've been trying to run a part of code that creates a facet_wrap() graph in r, and it worked very well for my porpouse but the x axis labels are overlapping each other.
I need to rotate them 45 degrees.
I've been trying to run this code for the porpouse and it did create the graph, but the x axis label didn't rotate as I expected.

Here is the code:

for (x in unique(clss_perc_factor7$Horto)){
  ggsave(paste('barplot_esp40', x, sep = '_'), 
         ggplot(clss_perc_factor7[clss_perc_factor7$Horto == x,], 
                aes(x = Classe, 
                    y = Freq_perc)) +
           theme(plot.title = element_text(hjust = 0.5), 
                 axis.text.x = element_text(angle = 45, hjust = 1)) +
           theme_bw() +
           geom_bar(stat = 'identity', 
                    colour = 'black', 
                    fill = '#66CC99') +
           facet_wrap(~ CD_TALHAO) +
           labs(x = 'Classe de Espaçamento', 
                y = 'Nº de Indivíduos (%)', 
                title = 'Distribuição do Espaçamento em Classes'),
         dpi = 'retina',
         device = 'png')
}

Given that:

  • clss_perc_factor7 is the data frame with more then one forest garden ("Horto" - in the loop).
  • In each forest garden there are different productive units ("CD_TALHAO" - in facet_wrap())
  • That's why I'm using a for loop to plot the graphs.

OBS: The part theme(plot.title = element_text(hjust = 0.5)... which was supposed to align the title to center isn't working either.

Thanks a lot guys!


Solution

  • Here is a way:

    library(ggplot2)
    ggplot(mtcars,aes(hp,mpg)) +
      geom_point() + 
      facet_wrap(~cyl) +
      theme(strip.text.x = element_text(angle = 45)) 
    

    Good luck!