1

Estoy intentando realizar mediante Run ggplot para varios conjuntos de datos. Mi idea es que utilicen el mismo patrón de colores, para ello he añadido una columna nueva en el dataframe original:

    labels1 <- LC_pos_primc$Descripcion
    colours1 <- LC_pos_primc$colors


    ggplot(LC_pos_primc, 
           aes(y = f, x = reorder(Descripcion, -f),fill=Descripcion)) +
      geom_bar(stat = "identity") +
      coord_flip() +
      labs(title = "Ranking dx Primarios Pacientes LC+",
           x = "Dx Primarios",
           y = "% respecto al total de Dx Primarios") +
      scale_y_continuous(expand = expansion(mult = c(0, 0)), lim = c(0, 40)) +
      scale_fill_manual(values = colours1, labels = labels1) +
      my_theme()->plotA


      labels2<- LC_neg_primc$Descripcion
      colours2<- LC_neg_primc$colors


      ggplot(LC_neg_primc, 
           aes(y = f, x = reorder(Descripcion, -f), fill = Descripcion)) +
      geom_bar(stat = "identity") +
      coord_flip() +
      labs(title = "Ranking dx Primarios Pacientes LC-",
           x = "Dx Primarios",
           y = "% respecto al total de Dx Primarios")+
      scale_y_continuous(expand = expansion(mult = c(0, 0)), lim = c(0, 40)) +
      scale_fill_manual(values = colours2, labels = labels2) +
      my_theme()->plotB

que luego cuando junto ambos ggplots veo que no tienen el mismo patrón de colores según cada causa de la descripcion:

      ggarrange(plotA,
                plotB,
                labels = c("A","B",ncols=2))

introducir la descripción de la imagen aquí

por ejemplo la causa XXII tiene un color diferente en ambos ggplots.

Entonces he revisado el dataframe del que se originaron las etiquetas y colores:

                labels1
                 [1] "IX-Diseases of the circulatory system"                                                                    
                 [2] "XVIII-Symptoms, signs, and abnormal clinical \nand laboratory findings, not elsewhere classified"         
                 [3] "X-Diseases of the respiratory system"                                                                     
                 [4] "XIII-Diseases of the musculoskeletal \nsystem and connective tissue"                                      
                 [5] "II-Neoplasms"                                                                                             
                 [6] "XI-Diseases of the digestive system"                                                                      
                 [7] "XIV-Diseases of the genitourinary system"                                                                 
                 [8] "IV-Endocrine, nutritional, and metabolic diseases"                                                        
                 [9] "VI-Diseases of the nervous system"                                                                        
                [10] "III-Diseases of the blood and blood-forming organs and \ncertain disorders involving the immune mechanism"
                [11] "XIX-Injury, poisoning, and certain other \nconsequences of external causes"                               
                [12] "XXII-Codes for special purposes"                                                                          
                [13] "I-Certain infectious and parasitic diseases"                                                              
                [14] "XXI-Factors influencing health status and contact with health services"                                   
                [15] "XV-Pregnancy, childbirth, and the puerperium"  

                                                       
                colours1
                 [1] "#A52A2A" "#FF4500" "#CCCCCC" "#FAFAD2" "#FFA500" "#000000" "#FFD700" "#00FF00" "#FF00FF" "#FFFF00"
                [11] "#8B0000" "#9932CC" "#FF0000" "#006400" "#00FFD4"


                labels2
                 [1] "XXII-Codes for special purposes"                                                                          
                 [2] "X-Diseases of the respiratory system"                                                                     
                 [3] "IX-Diseases of the circulatory system"                                                                    
                 [4] "XI-Diseases of the digestive system"                                                                      
                 [5] "II-Neoplasms"                                                                                             
                 [6] "XIV-Diseases of the genitourinary system"                                                                 
                 [7] "XVIII-Symptoms, signs, and abnormal clinical \nand laboratory findings, not elsewhere classified"         
                 [8] "XIX-Injury, poisoning, and certain other \nconsequences of external causes"                               
                 [9] "XIII-Diseases of the musculoskeletal \nsystem and connective tissue"                                      
                [10] "XV-Pregnancy, childbirth, and the puerperium"                                                             
                [11] "III-Diseases of the blood and blood-forming organs and \ncertain disorders involving the immune mechanism"
                [12] "I-Certain infectious and parasitic diseases"                                                              
                [13] "VI-Diseases of the nervous system"                                                                        
                [14] "XXI-Factors influencing health status and contact with health services"                                   
                [15] "IV-Endocrine, nutritional, and metabolic diseases"                                                        
                [16] "V-Mental and behavioral disorders"                                                                        
                [17] "XII-Diseases of the skin and subcutaneous tissue"                                                         
                [18] "VII-Diseases of the eye and adnexa"                                                                       
                [19] "VIII-Diseases of the ear and mastoid process"                                                             
                [20] "XVI-Certain conditions originating in the perinatal period"                                               
                [21] "XVII-Congenital malformations, deformations, and chromosomal abnormalities"                               
                
                colours2
                 [1] "#9932CC" "#CCCCCC" "#A52A2A" "#000000" "#FFA500" "#FFD700" "#FF4500" "#8B0000" "#FAFAD2" "#00FFD4"
                [11] "#FFFF00" "#FF0000" "#FF00FF" "#006400" "#00FF00" "#0000FF" "#FFFFFF" "#00FFFF" "#FF00D4" "#800080"
                [21] "#008080"

He encontrado que al realizar uno solo la leyenda tiene unos colores que no corresponden con los del ggplot:

introducir la descripción de la imagen aquí ¿Dónde está el fallo? ¿Cómo solucionarlo? Gracias de antemano.

1 respuesta 1

1

El problema básicamente es que los colores deberían respetar el mismo orden en ambos vectores, pero, en este caso, dónde además tienes categorías distintas, la forma más cómoda de establecer los colores para que sean consistentes entre los dos gráficos es mediante un vector con nombre, dónde cada valor de color esta nombrado con la categoría a la cual se le aplica:

colores1 <- setNames(LC_pos_primc$colors, LC_pos_primc$Descripcion) 
colores2 <- setNames(LC_neg_primc$color, LC_neg_primc$Descripcion) 

Luego simplemente puedes hacer:

scale_fill_manual(values = colores1, labels=names(colores1))  

y

scale_fill_manual(values = colores2, labels=names(colores2))  
1
  • Gracias Patricio, funciona perfectamente Commented el 4 ago. 2023 a las 12:02

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.