rggplot2graphics

Problem using ggplot (correct order in x axis)


I am having some problems using ggplot. Sometime ago in the same part of my script I endure the problem below:

Problems using ggplot, assing(paste0)) in a for loop

That problem was solved using the answer given by Rui Barradas.

But I had to alter some things in the script and some graphics were being plotted with the order in the x axis wrong.

The code I am using is:

    AUX_HIST_NOT_LIST <- AUX_GRAF %>%
  pivot_longer(-SE, names_to = "Municipios") %>% 
  mutate(
    SE = SE,
    Municipios = gsub("_", " ", Municipios)
  ) %>%
  group_split(Municipios) %>% 
  lapply(\(dados) {
    titulo <- dados$Municipios %>% 
      unique() %>% 
      paste0(" - Notificados")
    ggplot(dados, aes(x = SE, 
                      y = value)
    ) + 
      geom_col(color = "black", 
               fill = "#8FBC8F") + 
      geom_label(aes(label = value), 
                 alpha = 0.5, 
                 vjust = 0.1) +
      labs(
        caption = Fonte, 
        x = "Semana Epidemiológica",
        y = "Número de Casos",
        title = titulo
      ) +
      scale_y_continuous(expand = expansion(mult = c(0, 0.2))) +
      Theme_Hist()
  })

RS_2025_GRAF_Histograma_Notificados_01 <- (AUX_HIST_NOT_LIST[[1]] + AUX_HIST_NOT_LIST[[2]]) / 
  (AUX_HIST_NOT_LIST[[3]] + AUX_HIST_NOT_LIST[[4]]) / 
  (AUX_HIST_NOT_LIST[[5]] + AUX_HIST_NOT_LIST[[6]]) / 
  (AUX_HIST_NOT_LIST[[7]] + AUX_HIST_NOT_LIST[[8]]) 

RS_2025_GRAF_Histograma_Notificados_02 <- (AUX_HIST_NOT_LIST[[9]] + AUX_HIST_NOT_LIST[[10]]) / 
  (AUX_HIST_NOT_LIST[[11]] + AUX_HIST_NOT_LIST[[12]]) / 
  (AUX_HIST_NOT_LIST[[13]] + AUX_HIST_NOT_LIST[[14]]) / 
  (AUX_HIST_NOT_LIST[[15]] + AUX_HIST_NOT_LIST[[16]]) 

The X axis need to be in a numeric order. In the others graphics I was able to correct the situation, but in this case, the script is more sophisticated than I can manage.

the data frame I need to use is the:

dput(head(AUX_GRAF))
structure(list(SE = c("2", "3", "4", "5", "6", "7"), ARAPUÃ = c(0, 
1, 0, 1, 3, 1), ARIRANHA_DO_IVAÍ = c(0, 0, 0, 2, 1, 0), CÂNDIDO_DE_ABREU = c(0, 
0, 3, 2, 0, 4), CRUZMALTINA = c(0, 0, 0, 1, 1, 1), GODOY_MOREIRA = c(3, 
1, 0, 2, 3, 1), IVAIPORÃ = c(5, 8, 2, 10, 9, 6), JARDIM_ALEGRE = c(0, 
0, 1, 4, 1, 0), LIDIANÓPOLIS = c(0, 1, 0, 1, 0, 0), LUNARDELLI = c(0, 
2, 0, 3, 0, 2), MANOEL_RIBAS = c(3, 3, 3, 1, 2, 6), MATO_RICO = c(0, 
1, 0, 0, 0, 0), NOVA_TEBAS = c(0, 0, 1, 0, 0, 1), RIO_BRANCO_DO_IVAÍ = c(0, 
1, 0, 1, 0, 1), ROSÁRIO_DO_IVAÍ = c(0, 0, 0, 0, 0, 0), SANTA_MARIA_DO_OESTE = c(0, 
2, 1, 2, 8, 9), SÃO_JOÃO_DO_IVAÍ = c(2, 8, 2, 4, 5, 5)), row.names = c(NA, 
6L), class = "data.frame")

EDIT:

The object Fonte is an object common on several graphics. It is the source of my data. Each time I run the script I change the content of the object.

Fonte <- "Fonte: SINAN. BASE DBF acessada em 28/01/2025"   ##### Fonte dos gráficos relacionados ao SINAN

Fonte_1 <- "Fonte: Lacen. Acesso em 30/01/2025"            ##### Fonte dos gráficos relacionados ao LACEN

Fonte_2 <- "Fonte: Planilhas de Controle Municipais. Acesso em 30/01/2025"     ##### Fonte dos gráficos relacionados às Planilhas Municipais

Theme_list is a function I use, again, on several graphics:

Theme_Hist <- function(){ 
  theme_minimal(base_size = 10) %+replace%  
    theme(
      axis.text.x = element_text(face = "bold"),
      panel.grid.major = element_line(color = "#C0C0C0"),
      panel.grid.minor = element_blank(),
      panel.background = element_rect(fill = "#F5F5F5"),
      plot.title = element_text(face = "bold", 
                                size = 15, 
                                colour = "#556B2F")
    )
}

The image above is my output. The X axis begins with "11", then blank, "3", "4", "5", "6",...

But should be: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11


Solution

  • If I understand correctly, you can do what Jon Spring said aes(x = as.numeric(SE), ... but slightly modified as sorted factor

    AUX_GRAF$SE <- factor(as.numeric(AUX_GRAF$SE), levels = sort(unique(as.numeric(AUX_GRAF$SE))))

    In your example you gave SE e [2:7] which gives

    out

    Code

    suppressPackageStartupMessages({
      library(dplyr)
      library(tidyr)
      library(ggplot2)
      library(patchwork)
    })
    
    Theme_Hist <- function(){ 
      theme_minimal(base_size = 10) %+replace%  
        theme(
          axis.text.x = element_text(face = "bold"),
          panel.grid.major = element_line(color = "#C0C0C0"),
          panel.grid.minor = element_blank(),
          panel.background = element_rect(fill = "#F5F5F5"),
          plot.title = element_text(face = "bold", 
                                    size = 15, 
                                    colour = "#556B2F")
        )
    }
    
    Fonte <- "Fonte: SINAN. BASE DBF acessada em 28/01/2025"   ##### Fonte dos gráficos relacionados ao SINAN
    
    AUX_GRAF <- structure(list(SE = c("2", "3", "4", "5", "6", "7"), ARAPUÃ = c(0, 
                                                                                1, 0, 1, 3, 1), ARIRANHA_DO_IVAÍ = c(0, 0, 0, 2, 1, 0), CÂNDIDO_DE_ABREU = c(0, 
                                                                                                                                                             0, 3, 2, 0, 4), CRUZMALTINA = c(0, 0, 0, 1, 1, 1), GODOY_MOREIRA = c(3, 
                                                                                                                                                                                                                                  1, 0, 2, 3, 1), IVAIPORÃ = c(5, 8, 2, 10, 9, 6), JARDIM_ALEGRE = c(0, 
                                                                                                                                                                                                                                                                                                     0, 1, 4, 1, 0), LIDIANÓPOLIS = c(0, 1, 0, 1, 0, 0), LUNARDELLI = c(0, 
                                                                                                                                                                                                                                                                                                                                                                        2, 0, 3, 0, 2), MANOEL_RIBAS = c(3, 3, 3, 1, 2, 6), MATO_RICO = c(0, 
                                                                                                                                                                                                                                                                                                                                                                                                                                          1, 0, 0, 0, 0), NOVA_TEBAS = c(0, 0, 1, 0, 0, 1), RIO_BRANCO_DO_IVAÍ = c(0, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   1, 0, 1, 0, 1), ROSÁRIO_DO_IVAÍ = c(0, 0, 0, 0, 0, 0), SANTA_MARIA_DO_OESTE = c(0, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   2, 1, 2, 8, 9), SÃO_JOÃO_DO_IVAÍ = c(2, 8, 2, 4, 5, 5)), row.names = c(NA, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          6L), class = "data.frame")
    
    # Convert SE to numeric
    AUX_GRAF$SE <- factor(as.numeric(AUX_GRAF$SE), levels = sort(unique(as.numeric(AUX_GRAF$SE))))
    
    AUX_HIST_NOT_LIST <- AUX_GRAF %>%
      pivot_longer(-SE, names_to = "Municipios") %>% 
      mutate(
        Municipios = gsub("_", " ", Municipios)
      ) %>%
      group_split(Municipios) %>% 
      lapply(\(dados) {
        titulo <- dados$Municipios %>% 
          unique() %>% 
          paste0(" - Notificados")
        ggplot(dados, aes(x = SE, 
                          y = value)
        ) + 
          geom_col(color = "black", 
                   fill = "#8FBC8F") + 
          geom_label(aes(label = value), 
                     alpha = 0.5, 
                     vjust = 0.1) +
          labs(
            caption = Fonte, 
            x = "Semana Epidemiológica",
            y = "Número de Casos",
            title = titulo
          ) +
          scale_y_continuous(expand = expansion(mult = c(0, 0.2))) +
          Theme_Hist()
      })
    
    # Using patchwork here
    RS_2025_GRAF_Histograma_Notificados_01 <- (AUX_HIST_NOT_LIST[[1]] | AUX_HIST_NOT_LIST[[2]]) / 
      (AUX_HIST_NOT_LIST[[3]] | AUX_HIST_NOT_LIST[[4]]) / 
      (AUX_HIST_NOT_LIST[[5]] | AUX_HIST_NOT_LIST[[6]]) / 
      (AUX_HIST_NOT_LIST[[7]] | AUX_HIST_NOT_LIST[[8]])
    
    RS_2025_GRAF_Histograma_Notificados_01
    
    RS_2025_GRAF_Histograma_Notificados_02 <- (AUX_HIST_NOT_LIST[[9]] | AUX_HIST_NOT_LIST[[10]]) / 
      (AUX_HIST_NOT_LIST[[11]] | AUX_HIST_NOT_LIST[[12]]) / 
      (AUX_HIST_NOT_LIST[[13]] | AUX_HIST_NOT_LIST[[14]]) / 
      (AUX_HIST_NOT_LIST[[15]] | AUX_HIST_NOT_LIST[[16]])
    
    RS_2025_GRAF_Histograma_Notificados_02