Tutorial sobre como hacer varios gráficos en un loop, en R.

Puedes seguir el tutorial por vídeo en https://www.youtube.com/watch?v=PdcJA6KawVE
El script lo tienes disponible en http://rpubs.com/Rortizdu/142325

Empezamos estableciendo el directorio de trabajo.

setwd("~/Expression/Expression Encoder/Output/44 GGPLOT2. Graficos en loop")

Cargar datos

http://www.magrama.gob.es/es/estadistica/temas/estadisticas-agrarias/agricultura/esyrce/

Datos = read.table("Encuesta.csv", header=T, sep=",", dec=".", na.strings = "", fileEncoding = "latin1")
head(Datos)
##          CultivoOCubierta  Secano Regadío Invernadero   Total
## 1              TRIGO DURO  431764   51074          NA  482838
## 2 TRIGO BLANDO Y SEMIDURO 1610186  189920          NA 1800106
## 3    CEBADA DE 2 CARRERAS 2369828  220530          NA 2590359
## 4    CEBADA DE 6 CARRERAS  241303   13254          NA  254557
## 5                   AVENA  392150   11168          NA  403318
## 6                 CENTENO  151040    1416          NA  152456
##                 Grupo
## 1 CEREALES GRANO (CE)
## 2 CEREALES GRANO (CE)
## 3 CEREALES GRANO (CE)
## 4 CEREALES GRANO (CE)
## 5 CEREALES GRANO (CE)
## 6 CEREALES GRANO (CE)
str(Datos)
## 'data.frame':    151 obs. of  6 variables:
##  $ CultivoOCubierta: Factor w/ 151 levels "ACEITUNA DE ALMAZARA",..: 140 139 34 35 22 37 141 94 20 84 ...
##  $ Secano          : int  431764 1610186 2369828 241303 392150 151040 155506 31317 NA 22092 ...
##  $ Regadío         : int  51074 189920 220530 13254 11168 1416 3600 162 112631 401588 ...
##  $ Invernadero     : int  NA NA NA NA NA NA NA NA NA NA ...
##  $ Total           : int  482838 1800106 2590359 254557 403318 152456 159106 31479 112631 423680 ...
##  $ Grupo           : Factor w/ 18 levels "BARBECHOS ","CEREALES GRANO (CE)",..: 2 2 2 2 2 2 2 2 2 2 ...

Gráfico de barras con todos los cultivos.

library(ggplot2)
ggplot(Datos, aes(CultivoOCubierta, Total)) +
    geom_bar(stat="identity") +
    theme(axis.text.x  = element_text(angle=90))
## Warning: Removed 2 rows containing missing values (position_stack).

Gráfico de barras con un grupo de cultivos.

levels(Datos$Grupo)
##  [1] "BARBECHOS "                  "CEREALES GRANO (CE)"        
##  [3] "FORRAJERAS (FO)"             "FRUTALES CITRICOS (CI)"     
##  [5] "FRUTALES NO CITRICOS (FR)"   "HORTALIZAS Y FLORES (HO)"   
##  [7] "HUERTOS FAMILIARES"          "INDUSTRIALES (IN)"          
##  [9] "INVERNADEROS VACIOS"         "LEGUMINOSAS GRANO (LE)"     
## [11] "OLIVAR (OL)"                 "OTRAS SUPERFICIES"          
## [13] "OTROS CULTIVOS LEÑOSOS (OC)" "PRADOS Y PASTIZALES"        
## [15] "SUPERFICIE FORESTAL"         "TUBERCULOS C H (TU)"        
## [17] "VIÑEDO (VI)"                 "VIVEROS (VV)"
Datos$TotalMilloha=round((Datos$Total/1000000),2)
head(Datos)
##          CultivoOCubierta  Secano Regadío Invernadero   Total
## 1              TRIGO DURO  431764   51074          NA  482838
## 2 TRIGO BLANDO Y SEMIDURO 1610186  189920          NA 1800106
## 3    CEBADA DE 2 CARRERAS 2369828  220530          NA 2590359
## 4    CEBADA DE 6 CARRERAS  241303   13254          NA  254557
## 5                   AVENA  392150   11168          NA  403318
## 6                 CENTENO  151040    1416          NA  152456
##                 Grupo TotalMilloha
## 1 CEREALES GRANO (CE)         0.48
## 2 CEREALES GRANO (CE)         1.80
## 3 CEREALES GRANO (CE)         2.59
## 4 CEREALES GRANO (CE)         0.25
## 5 CEREALES GRANO (CE)         0.40
## 6 CEREALES GRANO (CE)         0.15
GraficoCultivos = 
    ggplot(subset(Datos, Grupo=="CEREALES GRANO (CE)"), 
       aes(x=reorder(CultivoOCubierta,-TotalMilloha), y=TotalMilloha, fill=CultivoOCubierta)) +
    geom_bar(stat="identity") +
    theme_bw() +
    labs(title="Superficie en España de Cereales",
         x="Cultivo",
         y="Superficie (Millones ha)") +
    theme(text = element_text(size=12), # Tamaño de fuente del gráfico por defecto
          plot.title = element_text(size=rel(2), # Tamaño del título, doble del establecido por defecto
                                    vjust=2, #Justificación vertical, para separarlo del gráfico
                                    face="bold", #Letra negrilla
                                    color="darkgreen", #Color del texto
                                    lineheight=1.5), #Separación entre líneas)
          axis.text.x = element_text(angle = 45, hjust = 1),
          legend.position="none",
          axis.title.x = element_text(face="bold", vjust=1.5, colour="darkgreen", size=rel(1.5)),
          axis.title.y = element_text(face="bold", vjust=1.5, colour="darkgreen", size=rel(1.5)),
          axis.text = element_text(colour = "black")) +
    coord_cartesian(ylim=c(0, 3)) +
    scale_y_continuous(breaks =seq(0, 3, 0.5))

GraficoCultivos

Gráfico de barras para cada grupo de cultivos.

Datos$TotalMilesha=round((Datos$Total/1000),2)

ListaGrupos = unique(Datos$Grupo) #Lista con los niveles de la variable Grupo

for (i in seq_along(ListaGrupos)) {  #Para cada uno de los valores de la lista...
    GraficoCultivos =
        ggplot(subset(Datos, Datos$Grupo==ListaGrupos[i]),
                aes(x=reorder(CultivoOCubierta,-TotalMilesha), y=TotalMilesha, fill=CultivoOCubierta)) +
           geom_bar(stat="identity") +
           theme_bw() +
           labs(x="Cultivo",    #Elimino title de este apartado para configurarlo al final
                y="Superficie (Miles ha)") +
           theme(text = element_text(size=10),
                 plot.title = element_text(size=rel(2), vjust=2, face="bold", color="darkgreen", lineheight=1.5),
                 axis.text.x = element_text(angle = 45, hjust = 1),
                 legend.position="none",
                 axis.title.x = element_text(face="bold", vjust=1.5, colour="darkgreen", size=rel(1.5)),
                 axis.title.y = element_text(face="bold", vjust=1.5, colour="darkgreen", size=rel(1.5)),
                 axis.text = element_text(colour = "black")) +
           
           ggtitle(paste("Superficie en España de", ListaGrupos[i])) #Configuro un título por grupo
       
           print (GraficoCultivos) #Mostrar gráficos en la pantalla
}

## Warning: Removed 2 rows containing missing values (position_stack).

Gráfico de barras para cada grupo de cultivos y salvado.

resultado <- "C:/Users/Raul Ortiz/Documents/Expression/Expression Encoder/Output/44 GGPLOT2. Graficos en loop/Graficas/"

ListaGrupos = unique(Datos$Grupo) #Lista con los niveles de la variable Grupo

for (i in seq_along(ListaGrupos)) {  #Para cada uno de los valores de la lista...
    GraficoCultivos =
        ggplot(subset(Datos, Datos$Grupo==ListaGrupos[i]),
                aes(x=reorder(CultivoOCubierta,-TotalMilesha), y=TotalMilesha, fill=CultivoOCubierta)) +
           geom_bar(stat="identity") +
           theme_bw() +
           labs(x="Cultivo",    #Elimino title de este apartado para configurarlo al final
                y="Superficie (Miles ha)") +
           theme(text = element_text(size=12),
                 plot.title = element_text(size=rel(2), vjust=2, face="bold", color="darkgreen", lineheight=1.5),
                 axis.text.x = element_text(angle = 45, hjust = 1),
                 legend.position="none",
                 axis.title.x = element_text(face="bold", vjust=1.5, colour="darkgreen", size=rel(1.5)),
                 axis.title.y = element_text(face="bold", vjust=1.5, colour="darkgreen", size=rel(1.5)),
                 axis.text = element_text(colour = "black")) +
           
           ggtitle(paste("Superficie en España de", ListaGrupos[i])) #Configuro un título por grupo
       
           print (GraficoCultivos)
           
           # guardar gráfica como .jpeg
            ggsave(GraficoCultivos,                                        #nombre de la gráfica en R
                   file=paste(resultado, ListaGrupos[i], ".jpeg", sep=''), #Nombre del jpeg
                   height = 11, width = 18, dpi=300)                       #características del jpeg
}