admin管理员组

文章数量:1391925

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

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

Share Improve this question edited Mar 13 at 18:23 M-- 29.5k10 gold badges70 silver badges106 bronze badges Recognized by R Language Collective asked Mar 13 at 16:45 GustavoGustavo 356 bronze badges 5
  • Please start a new session and test to confirm if your code + data work with what you've provided. You should note that tidyverse and patchwork libraries are needed, and pls remove caption = Fonte and +Theme_Hist() since we don't have those. – Jon Spring Commented Mar 13 at 17:00
  • Can you link to a picture of your output, and/or describe how it is wrong? Mine looks fine I think. – Jon Spring Commented Mar 13 at 17:01
  • Sorry. I made some editions... – Gustavo Commented Mar 13 at 18:09
  • 2 In your example data, SE is loaded as a character variable, so it should sort alphabetically, with 11 coming before 2. It's possible in your data you have it as a factor, which might explain how you got 11 to show up before 2, which is before 10. Probably simplest to make it a numeric value to sort in numeric order. Does it resolve if you use aes(x = as.numeric(SE), ... in your plotting code? – Jon Spring Commented Mar 13 at 18:14
  • Apparently, it works!! But I would need that all columns had its own label. The number (label) in the columns are the last ten weeks, and each week they change. Now I only have 3, 6 and 9 in the columns. – Gustavo Commented Mar 13 at 19:09
Add a comment  | 

1 Answer 1

Reset to default 2

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

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

本文标签: rProblem using ggplot (correct order in x axis)Stack Overflow