html-parser.R 34.3 KB
Newer Older
1 2 3 4 5
# Script to count how many titles per hour that have certain words in home pages of newspapers.
# It generates some plots to view the data
# Ask @numeroteca or info@montera34.com for questions, suggestions and collaborations

# Load libraries -----
6 7
library(rvest)
library(stringr)
8
# library(R.utils) # opens gzip compresed file
9 10 11
library(gsubfn) # select text in the parenthesis with regex
library(tidyverse) # for ggplot

12 13
# Set search variables: words and datelimits -----
# word <- "Cifuentes|Javier Ramos|Enrique Álvarez Conde|Pablo Chico|María Teresa Feito|Alicia López de los Cobos|Cecilia Rosado|Clara Souto|Amalia Calonge|Universidad Rey Juan Carlos"
14
# word <- "vox|Vox|VOX|Santiago Abascal|ortega smith|francisco serrano"
numeroteca's avatar
numeroteca committed
15
# partidos y líderes
16 17
word1 <- "vox|Vox|VOX|Santiago Abascal|Abascal"
word2 <- "Podemos|Pablo Iglesias|Iglesias"
18 19
word3 <- "PP|Pablo Casado|Casado"
word4 <- "PSOE|Pedro Sánchez|Sánchez"
numeroteca's avatar
numeroteca committed
20
word5 <- "C's|Cs|Ciudadanos|Albert Rivera|Rivera"
21 22
word6 <- "PACMA|Silvia Barquero|Barquero"

numeroteca's avatar
numeroteca committed
23 24 25 26 27 28 29 30
# partidos y líderes
word1 <- "vox|Vox"
word2 <- "vox|Vox|VOX"
word3 <- "vox|Vox|VOX|Abascal"
word4 <- "vox|Vox|VOX|Santiago Abascal|Abascal"
word5 <- "vox|Vox|VOX|Santiago Abascal|Abascal|Ortega Smith"
word6 <- "vox|Vox|VOX|Santiago Abascal|Abascal|Ortega Smith|Rocio Monasterio|Monasterio"

31 32 33 34 35 36 37 38 39 40 41
word  <- ""
word <- data.frame(matrix(ncol = 1,nrow = 6 ))
names(word)  <- c("word")

word$word[1] <- word1
word$word[2] <- word2
word$word[3] <- word3
word$word[4] <- word4
word$word[5] <- word5
word$word[6] <- word6

numeroteca's avatar
numeroteca committed
42
# # Select word to be displayed in plots
43 44
word1_explain <- "VOX" #
word2_explain <- "Podemos" #
45 46 47 48 49
word3_explain <- "PP" #
word4_explain <- "PSOE" #
word5_explain <- "Cs" #
word6_explain <- "PACMA" #

numeroteca's avatar
numeroteca committed
50 51 52 53 54 55 56 57
# # Select word to be displayed in plots
word1_explain <- "VOXmin" #
word2_explain <- "VOXmay" #
word3_explain <- "VOXabascal" #
word4_explain <- "VOXsantiagoabascal" #
word5_explain <- "VOXortega" #
word6_explain <- "VOXmonasterio" #

58 59 60 61 62 63
word$explain[1] <- word1_explain
word$explain[2] <- word2_explain
word$explain[3] <- word3_explain
word$explain[4] <- word4_explain
word$explain[5] <- word5_explain
word$explain[6] <- word6_explain
64 65

# Set time limits
numeroteca's avatar
numeroteca committed
66
my_limit <- c(as.POSIXct("2019-04-01 00:00:01"), as.POSIXct("2019-04-26 00:12:01"))
67
my_init <- as.POSIXlt("2019-04-12 00:00:00")
68 69

# open compressed file
70 71
# gunzip("eldiario/http!www.eldiario.es!!!!@2018-04-06T23:01:07.888847+00:00.gz",remove=FALSE)
# no hace falta, read_html lee el .gz sin necesidad de descomprimir
72

73
# --------- Create data frame with all the newspapers + time and date---------------
74

75 76 77 78
# Read list of files. The list has been generated with this bash script, 
  # when you are located in the directory with all the .gz files: 
  # for f in *.gz; do echo "$f" >> mylist.txt; done
# CHANGE THIS: write path where your mylist.file is located
79
list <- read_csv("data/mylist.txt")
80 81
# add name to the one column file
names(list) <- "urls"
82 83

# extract name of newspaper
84 85
list$urls  <-  sub("file './", "", list$urls )
list$urls <-  sub("'", "", list$urls)
86
list$newspaper <- strapplyc( as.character(list$urls), "[a-z]*!([a-z]{1,61}.[a-zA-Z]{2,})", simplify = TRUE)
87

88 89 90 91 92 93 94 95 96 97 98
# list$newspaper <- as.factor(list$newspaper) No funciona convertirlo a factor
list$newspaper <-  sub("www.", "", list$newspaper)

# extract year,month, day, hour
list$year <- as.numeric(strapplyc( as.character(list$urls), ".*@([0-9]*)", simplify = TRUE))
list$month <- as.numeric(strapplyc( as.character(list$urls), ".*@[0-9]*-([0-9]*)", simplify = TRUE))
list$day <- as.numeric(strapplyc( as.character(list$urls), ".*@[0-9]*-[0-9]*-([0-9]*)", simplify = TRUE))
list$hour <- as.numeric(strapplyc( as.character(list$urls), ".*@[0-9]*-[0-9]*-[0-9]*T([0-9]*)", simplify = TRUE))

# create date
list$date <- as.Date( paste(list$day,"/",list$month,"/",list$year,sep = "" ), "%d/%m/%Y")
99
list$timestamp <- as.POSIXlt( paste(list$year,"-",list$month,"-",list$day," ",list$hour,":00:00", sep = "" ))
100

101
# Save created list of front pages 
102
save(list,file="data/list.Rda")
103 104

# You can avoid all of the above and just load the existing file
105 106
load("data/list.Rda")

107 108 109 110 111 112
# Check visually if files exists
ggplot(list[list$newspaper == "larazon", ]) +
  geom_point(aes(x=date,y=month), alpha = 0.005)

# Process home pages ---------------------------

113 114
# Create list of selected pages. Select timeframe, newspapers
selected <- list[(list$newspaper == "eldiario" | list$newspaper == "elconfidencial" | 
115
                    list$newspaper == "elpais"| list$newspaper == "larazon" | list$newspaper == "elespanol") &
116
                   # list$date > "2018-10-01", ]
numeroteca's avatar
numeroteca committed
117
                   list$date > "2019-03-31", ]
118

119
# Create results dataframe
120 121 122 123
results <- ""
results <- data.frame(matrix(ncol = 1,nrow = nrow(selected)  ))
names(results)  <- c("newspaper")

124
# Loop to count how many titles per homepages have certain words
125
for (i in 1:nrow(selected)) {
126
  page <- read_html( paste("../storytracker/data-homepages/",selected$urls[i], sep = "") )
127
  
128
  if ( selected$newspaper[i] == "eldiario" | selected$newspaper[i] == "elpais" | selected$newspaper[i] == "larazon") {
129 130 131
    # eldiario
    # gets all the text in article titles. All articles are in h2 except the comics.
    titles <- page %>% html_nodes("article h2 a") %>% html_text() %>% data.frame()
132
  } else if ( selected$newspaper[i] == "elconfidencial" | selected$newspaper[i] == "elmundo" | selected$newspaper[i] == "elespanol") {
133 134
    titles <- page %>% html_nodes("article h3 a") %>% html_text() %>% data.frame()
  }
135
  colnames(titles) <- "title"
136
  # titles$title <- as.character(titles$title)
137
  
138
  # newspaper name
139
  results$newspaper[i] <- selected$newspaper[i]
140 141
  
  # insert date and time
142 143 144
  results$day[i] <- selected$day[i]
  results$month[i] <- selected$month[i]
  results$year[i] <- selected$year[i]
145 146 147 148 149
  results$hour[i] <- selected$hour[i] 
  
  # total of articles with link
  n_news <- nrow(titles)
  print(paste("nº noticias:",n_news))
150
  results$n_news[i] <- n_news
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  
  # select news that contain cerating 
  for (j in 1:nrow(word)) {
  # for (j in 1:5) {
    selected_news <- data.frame(titles[grepl(word$word[j], titles$title),])
    
    # Results
    # number of articles that contain words
    n_selected_news <- nrow(selected_news)
    print(paste("1 nº noticias con las palabras",word$explain[j],n_selected_news))
    # print(selected_news)
    # Percentage of articles that contain words
    percent <- round(n_selected_news / n_news * 100, digits = 2)
    print(paste("2 percent ",word$explain[j],percent))
    
    results$a <- 0
    results$b <- 0
    results$c <- 0
    results$d <- 0
    results$e <- 0
    results$f <- 0
    results$aa <- 0
    results$bb <- 0
    results$cc <- 0
    results$dd <- 0
    results$ee <- 0
    results$ff <- 0
    results$aaa <- 0
    results$bbb <- 0
    results$ccc <- 0
    results$ddd <- 0
    results$eee <- 0
    results$fff <- 0
    
    # create column with variable names
    names(results)[6+j] <- paste0("n_selected_news_",j,"_",word$explain[j])
    names(results)[7+j+nrow(word)] <- paste0("percent_",j,"_",word$explain[j])
    names(results)[8+j+2*nrow(word)] <- paste0("titles_",j,"_",word$explain[j])
    
    # insert value in results$n_selected_news_word_explain
    results[i,6+j] <- as.integer(n_selected_news)
    results[i,7+j+nrow(word)] <- percent
    results[i,8+j+2*nrow(word)] <- sapply(as.list(selected_news), paste0, collapse=";   ") 
    
  }
196
  
197
  print(paste("year:",selected$year[i], "month:",selected$month[i], "day:",selected$day[i],"hour:",selected$hour[i],selected$newspaper[i]))
198 199
}

200
results <- results %>% select(-a,-b,-c,-d,-e,-f,-aa,-bb,-cc,-dd,-ee,-ff,-aaa,-bbb,-ccc,-ddd,-eee,-fff)
201

202 203 204 205 206 207 208 209 210
# results5 <- ""
# results5 <- data.frame(matrix(ncol = 1,nrow = 5  ))
# names(results5)  <- c("newspaper")
# x <- as.list(selected_news2)
# results5$titles2[1] <- sapply(x, paste0, collapse=";    ") 
# 
# y <- as.character(selected_news1[1,1])
# writeLines(iconv(readLines("tmp.html"), from = "ANSI_X3.4-1986", to = "UTF8"), "tmp2.html")
# iconv(selected_news2[,1], 'utf-8', 'ascii', sub='')
211

212
# creates time stampt
213
results$date <- as.POSIXct( paste(results$year,"-",results$month,"-",results$day," ",results$hour,":00:00", sep = "" ))
214

215
# Save results 
216
# save(results,file="data/results-vox-01.Rda")
numeroteca's avatar
numeroteca committed
217 218
save(results,file="data/results-generales2019-6-partidos-1-25abril.Rda")
# save(results,file="data/results-vox-diferencias-busqueda.Rda")
219
# Load other results
220
# load("data/results-cifuentes-01.Rda")
221

222
# -----------Plot results para 1 o dos words buscadas ------------
223 224

# Plot para un único periódico
225 226 227 228
ggplot(data=results[results$newspaper=="eldiario",]) + ylim(c(0,100)) +
  geom_line(aes(x=date, y=n_news),color="#000000") +
  # geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
  # geom_line(aes(x=date, y=percent),color="#0000DD") +
229 230
  labs(title = paste("eldiario.es: noticias en portada.",sep = ""))

231 232 233
ggplot(data=results[results$newspaper=="eldiario",]) + # ylim(c(0,100)) +
  geom_line(aes(x=date, y=n_selected_news1),color="#000000") +
  geom_line(aes(x=date, y=n_selected_news2),color="#FF0000") +
234 235
  # geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
  # geom_line(aes(x=date, y=percent),color="#0000DD") +
236
  labs(title = paste("eldiario.es: noticias sobre ",word1_explain,sep = ""))
237

238
ggplot(data=results[results$newspaper=="eldiario",]) + # ylim(c(0,100)) +
239
  geom_line(aes(x=date, y=n_news),color="#000000") +
240 241
  geom_line(aes(x=date, y=n_selected_news1),color="#FF0000") +
  geom_line(aes(x=date, y=percent1),color="#0000DD") +
242
  labs(title = "eldiario.es: nº noticias en portada") +
243
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", limits = my_limit) 
244

245
ggplot(data=results[results$newspaper=="eldiario",]) + # ylim(c(0,100)) +
246
  geom_line(aes(x=date, y=n_news),color="#000000") +
247
  geom_line(aes(x=date, y=n_selected_news1),color="#FF0000") +
248
  # geom_line(aes(x=date, y=percent),color="#0000DD") +
249
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", limits = my_limit)  +
250
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
251
  geom_text(aes(x = as.POSIXct("2018-03-25 00:00:00"), 
252 253
                y = 19, label = "nº noticias sobre Cifuentes"), family = "Roboto Condensed", 
            color = "#FF0000", alpha=0.6, hjust = 0) +
254
  geom_text(aes(x = as.POSIXct("2018-03-25 00:00:00"), 
255 256
                y = 45, label = "nº noticias en portada", family = "Roboto Condensed"), 
            color = "#000000", alpha=0.6, hjust = 0) +
257
  labs(title = "eldiario.es: nº noticias en portada",
258 259 260 261 262
       subtitle = "21 marzo - 9 abril 2018. numeroteca.org",
       x = NULL,
       y = NULL,
       caption = "")

263
ggplot(data=results[results$newspaper=="eldiario",]) + #ylim(c(0,30)) +
264
  # geom_line(aes(x=date, y=n_news),color="#000000") +
265 266
  geom_line(aes(x=date, y=n_selected_news1),color="#FF0000") +
  geom_line(aes(x=date, y=percent1),color="#0000DD") +
267
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", 
268
                   limits = my_limit) +
269
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
270 271 272 273 274 275 276
  # geom_text(aes(x = as.POSIXct("2018-03-27 00:00:00"), 
  #               y = 1, label = "nº noticias sobre Cifuentes"), family = "Roboto Condensed", 
  #           color = "#FF0000", alpha=0.6, hjust = 0) +
  # geom_text(aes(x = as.POSIXct("2018-03-27 00:00:00"), 
  #               y = 15, label = "Porcentaje de noticias en portada", family = "Roboto Condensed"), 
  #           color = "#0000DD", alpha=0.6, hjust = 0) +
  labs(title = paste("eldiario.es: porcentaje noticias y nº noticias",word1_explain),
277 278 279 280 281 282
       subtitle = "21 marzo - 9 abril 2018. Datos: numeroteca.org",
       x = NULL,
       y = NULL,
       caption = "")


283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
ggplot(data=results[results$newspaper=="eldiario",]) + #ylim(c(0,30)) +
  # geom_line(aes(x=date, y=n_news),color="#000000") +
  # geom_line(aes(x=date, y=n_selected_news1),color="#FF0000") +
  geom_line(aes(x=date, y=percent1),color="#AA0000") +
  # geom_line(aes(x=date, y=n_selected_news2),color="#00FF00") +
  geom_line(aes(x=date, y=percent2),color="#00AA00") +
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", 
                   limits = my_limit) +
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  # geom_text(aes(x = as.POSIXct("2018-03-27 00:00:00"), 
  #               y = 1, label = "nº noticias sobre Cifuentes"), family = "Roboto Condensed", 
  #           color = "#FF0000", alpha=0.6, hjust = 0) +
  # geom_text(aes(x = as.POSIXct("2018-03-27 00:00:00"), 
  #               y = 15, label = "Porcentaje de noticias en portada", family = "Roboto Condensed"), 
  #           color = "#0000DD", alpha=0.6, hjust = 0) +
  labs(title = paste("eldiario.es: porcentaje noticias y nº noticias",word1_explain,"vs",word2_explain),
       subtitle = "21 marzo - 9 abril 2018. Datos: numeroteca.org",
       x = NULL,
       y = NULL,
       caption = "")

304 305 306 307 308
ggplot(data=results[results$newspaper=="elconfidencial",]) + ylim(c(0,10)) +
  # geom_line(aes(x=date, y=n_news),color="#000000") +
  geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
  geom_line(aes(x=date, y=percent),color="#0000DD") +
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", 
309
                   limits = my_limit) +
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  geom_text(aes(x = as.POSIXlt("2018-03-27 00:00:00"), 
                y = 5, label = "nº noticias sobre Cifuentes"), family = "Roboto Condensed", 
            color = "#FF0000", alpha=0.6, hjust = 0) +
  geom_text(aes(x = as.POSIXlt("2018-03-27 00:00:00"), 
                y = 3, label = "Porcentaje de noticias en portada", family = "Roboto Condensed"), 
            color = "#0000DD", alpha=0.6, hjust = 0) +
  labs(title = "elconfidencial.es: porcentaje noticias y nº noticias en portada sobre Cifuentes",
       subtitle = "21 marzo - 9 abril 2018. Datos: numeroteca.org",
       x = "Días",
       y = NULL,
       caption = "")


ggplot(data=results[results$newspaper=="elconfidencial",]) + ylim(c(0,10)) +
  # geom_line(aes(x=date, y=n_news),color="#000000") +
  geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
327
  geom_line(aes(x=date, y=percent),color="#0000DD") +
328
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", 
329
                   limits = my_limit) +
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  geom_text(aes(x = as.POSIXlt("2018-03-27 00:00:00"), 
                y = 5, label = "nº noticias sobre Cifuentes"), family = "Roboto Condensed", 
            color = "#FF0000", alpha=0.6, hjust = 0) +
  geom_text(aes(x = as.POSIXlt("2018-03-27 00:00:00"), 
                y = 3, label = "Porcentaje de noticias en portada", family = "Roboto Condensed"), 
            color = "#0000DD", alpha=0.6, hjust = 0) +
  labs(title = "elconfidencial.es: porcentaje noticias y nº noticias en portada sobre Cifuentes",
       subtitle = "21 marzo - 9 abril 2018. Datos: numeroteca.org",
       x = "Días",
       y = NULL,
       caption = "")

ggplot(data=results[results$newspaper=="elconfidencial",]) + ylim(c(0,120)) +
  geom_line(aes(x=date, y=n_news),color="#000000") +
  geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
  # geom_line(aes(x=date, y=percent),color="#0000DD") +
347
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", limits = my_limit) +
348 349 350 351 352 353 354 355 356 357 358 359
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  geom_text(aes(x = as.POSIXlt("2018-03-25 00:00:00"), 
                y = 19, label = "nº noticias sobre Cifuentes"), family = "Roboto Condensed", 
            color = "#FF0000", alpha=0.6, hjust = 0) +
  geom_text(aes(x = as.POSIXlt("2018-03-25 00:00:00"), 
                y = 45, label = "nº noticias en portada", family = "Roboto Condensed"), 
            color = "#000000", alpha=0.6, hjust = 0) +
  labs(title = "elconfidencial.es: nº noticias en portada - noticias sobre Cifuentes",
       subtitle = "21 marzo - 9 abril 2018. Datos: numeroteca.org",
       x = NULL,
       y = NULL,
       caption = "")
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

# Plot para un único periódico
ggplot(data=results[results$newspaper=="elconfidencial",]) + ylim(c(0,130)) +
  geom_line(aes(x=date, y=n_news),color="#000000") +
  geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
  geom_line(aes(x=date, y=percent),color="#0000DD") +
  labs(title = "elconfidencial: noticias sobre Cifuentes en portada (total, total selected, %)")

# Plot para un único periódico
ggplot(data=results[results$newspaper=="elpais",]) + ylim(c(0,130)) +
  geom_line(aes(x=date, y=n_news),color="#000000") +
  geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
  geom_line(aes(x=date, y=percent),color="#0000DD") +
  labs(title = "elPais: noticias sobre Cifuentes en portada (total, total selected, %)")

# Plot para un único periódico
ggplot(data=results[results$newspaper=="larazon",]) + ylim(c(0,130)) +
377
  geom_line(aes(x=date, y=n_news),color="#000000",size=0.1) +
378 379 380 381
  geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
  geom_line(aes(x=date, y=percent),color="#0000DD") +
  labs(title = "laRazon: noticias sobre Cifuentes en portada (total, total selected, %)")

382 383 384 385 386 387
# Plot para un único periódico
ggplot(data=results[results$newspaper=="elespanol",]) + ylim(c(0,140)) +
  geom_line(aes(x=date, y=n_news),color="#000000") +
  geom_line(aes(x=date, y=n_selected_news),color="#FF0000") +
  geom_line(aes(x=date, y=percent),color="#0000DD") +
  labs(title = "elespanol: noticias sobre Cifuentes en portada (total, total selected, %)")
388 389

# Plot para varios periódico
390 391
ggplot(data=results ) + ylim(c(0,140)) +
  geom_line(aes(x=date, y=n_news, group=newspaper),color="#000000",size=0.2) +
392 393 394 395 396 397 398 399
  geom_line(aes(x=date, y=n_selected_news, group=newspaper),color="#FF0000") +
  geom_line(aes(x=date, y=percent, group=newspaper),color="#0000DD") +
  labs(title = "elDiario - elconfidencial: noticias sobre Cifuentes en portada")

# Plot para varios periódico
ggplot(data=results ) + ylim(c(0,30)) +
  # geom_line(aes(x=date, y=n_news, group=newspaper),color="#000000") +
  # geom_line(aes(x=date, y=n_selected_news, group=newspaper),color="#FF0000") +
400
  geom_line(aes(x=date, y=percent, group=newspaper),color="#0000DD",size=0.4,alpha=0.6) +
401 402 403 404
  labs(title = "elDiario-elConfidencial-ElPais: % noticias sobre Cifuentes en portada")
# geom_text(aes(x = "2018-03-21", y = 500, label = "Gros"), color = "#9846dd", alpha=1) +
# geom_text(aes(x = "2007", y = 900, label = "Media"), color = "#000000", alpha=1) +
# geom_text(aes(x = "2007", y = 700, label = "Altza"), color = "#568ba5", alpha=1) +
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

# Plot para varios periódico ['#66c2a5','#fc8d62','#8da0cb','#e78ac3','#a6d854']
ggplot( ) + ylim(c(0,30)) +
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  geom_line(data=results[results$newspaper=="eldiario",], aes(x=date, y=percent, group=newspaper),color="#66c2a5",size=0.7) +
  geom_line(data=results[results$newspaper=="elconfidencial",], aes(x=date, y=percent, group=newspaper),color="#fc8d62",size=0.7) +
  geom_line(data=results[results$newspaper=="elpais",], aes(x=date, y=percent, group=newspaper),color="#8da0cb",size=0.7) +
  geom_line(data=results[results$newspaper=="larazon",], aes(x=date, y=percent, group=newspaper),color="#e78ac3",size=0.7) +
  geom_line(data=results[results$newspaper=="elespanol",], aes(x=date, y=percent, group=newspaper),color="#a6d854",size=0.7) +
  labs(title = "Porcentaje de noticias sobre Cifuentes en portada (cada hora)") +
  xlab("Días") +
  ylab("% noticias en portadas") +
  # theme(axis.text.y = element_text(size=10),
  #       # axis.title.y=element_blank(),
  #       axis.ticks.y =element_blank(),
  #       # axis.ticks.x =element_blank(),
  #       axis.text.x=element_text(size=9),
  #       axis.title.x=element_text(size=11),
  #       panel.grid.minor = element_blank(),
  #       panel.background = element_rect(fill="white"),
  #       panel.grid.major.y = element_line( size=.1, color="grey" ),
  #       # legend.position = "bottom",
  #       legend.text = element_text(size=15) ) +
  scale_y_continuous(breaks=seq(0,30,5)) +
429 430 431 432 433 434
  scale_x_datetime(date_breaks = "1 month", date_labels = "%m", limits = my_limit) +
  geom_text(aes(x = my_init, y = 11, label = "eldiario.es"), color = "#66c2a5", alpha=1, hjust = 0) +
  geom_text(aes(x = my_init, y = 13, label = "larazon.es"), color = "#e78ac3", alpha=1, hjust = 0) +
  geom_text(aes(x = my_init, y = 15, label = "elConfidencial.es"), color = "#fc8d62", alpha=1, hjust = 0) +
  geom_text(aes(x = my_init, y = 17, label = "elespanol.com"), color = "#a6d854", alpha=1, hjust = 0) +
  geom_text(aes(x = as.POSIXlt("2018-10-10 00:00:00"), y = 19, label = "elpais.com"), color = "#8da0cb", alpha=1, hjust = 0) +
435
  ylab ("% de noticias en portada") +
436 437
  labs(title = paste("Porcentaje de noticias sobre",word_explain,"en portada periódicos digitales"),
       subtitle = "01 oct 2018 - 18 enero 2019. Datos y visualización: numeroteca.org",
438
       x = "Días",
439
       y = "%",
440 441 442 443
       caption = "")

# Plot para varios periódico  
ggplot( ) + ylim(c(0,24)) +
444
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
445 446 447 448 449
  geom_line(data=results[results$newspaper=="eldiario",], aes(x=date, y=n_selected_news, group=newspaper),color="#66c2a5",size=0.7) +
  geom_line(data=results[results$newspaper=="elconfidencial",], aes(x=date, y=n_selected_news, group=newspaper),color="#fc8d62",size=0.7) +
  geom_line(data=results[results$newspaper=="elpais",], aes(x=date, y=n_selected_news, group=newspaper),color="#8da0cb",size=0.7) +
  geom_line(data=results[results$newspaper=="larazon",], aes(x=date, y=n_selected_news, group=newspaper),color="#e78ac3",size=0.7) +
  geom_line(data=results[results$newspaper=="elespanol",], aes(x=date, y=n_selected_news, group=newspaper),color="#a6d854",size=0.7) +
450 451 452 453 454 455 456 457 458 459 460 461 462 463
  # labs(title = "Número de noticias sobre Cifuentes en portada (cada hora)") +
  # xlab("Días") +
  # ylab("nº noticias en portadas") +
  # theme(axis.text.y = element_text(size=10),
  #       # axis.title.y=element_blank(),
  #       axis.ticks.y =element_blank(),
  #       axis.ticks.x =element_blank(),
  #       axis.text.x=element_text(size=9),
  #       axis.title.x=element_text(size=11),
  #       panel.grid.minor = element_blank(),
  #       panel.background = element_rect(fill="white"),
  #       panel.grid.major.y = element_line( size=.1, color="grey" ),
  #       # legend.position = "bottom",
  #       legend.text = element_text(size=15) ) +
464
  # scale_y_continuous(breaks=seq(0,30,5)) +
465 466 467 468 469 470 471 472
  scale_x_datetime(date_breaks = "1 month", date_labels = "%m", limits = my_limit) +
  geom_text(aes(x = my_init, y = 23, label = "eldiario.es"), color = "#66c2a5", alpha=1, hjust = 0) +
  geom_text(aes(x = my_init, y = 11, label = "larazon.es"), color = "#e78ac3", alpha=1, hjust = 0) +
  geom_text(aes(x = my_init, y = 17, label = "elConfidencial.es"), color = "#fc8d62", alpha=1, hjust = 0) +
  geom_text(aes(x = my_init, y = 20, label = "elespanol.com"), color = "#a6d854", alpha=1, hjust = 0) +
  geom_text(aes(x = my_init, y = 14, label = "elpais.com"), color = "#8da0cb", alpha=1, hjust = 0) +
  labs(title = paste("Número de noticias sobre",word_explain,"en portada periódicos digitales"),
     subtitle = "01 oct 2018 - 18 enero 2019. Datos y visualización: numeroteca.org",
473 474 475 476
     x = "Días",
     y = "nº noticias en portada",
     caption = "")

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

# Plot 6 research words ---------------------

# first method -----
ggplot(data=results[results$newspaper=="eldiario",]) + #ylim(c(0,30)) +
  geom_line(aes(x=date, y=percent_1_VOX),color="#00AA00") +
  geom_line(aes(x=date, y=percent_2_Podemos),color="#AAAA00") +
  geom_line(aes(x=date, y=percent_3_PP),color="#0000BB") +
  geom_line(aes(x=date, y=percent_4_PSOE),color="#DD0022") +
  geom_line(aes(x=date, y=percent_5_Cs),color="#FFAA44") +
  geom_line(aes(x=date, y=percent_6_PACMA),color="#555555") +
  
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", 
                   limits = my_limit) +
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  # geom_text(aes(x = as.POSIXct("2018-03-27 00:00:00"), 
  #               y = 1, label = "nº noticias sobre Cifuentes"), family = "Roboto Condensed", 
  #           color = "#FF0000", alpha=0.6, hjust = 0) +
  # geom_text(aes(x = as.POSIXct("2018-03-27 00:00:00"), 
  #               y = 15, label = "Porcentaje de noticias en portada", family = "Roboto Condensed"), 
  #           color = "#0000DD", alpha=0.6, hjust = 0) +
  labs(title = paste("eldiario.es: porcentaje noticias y nº noticias",word1_explain,"vs",word2_explain),
       subtitle = "21 marzo - 9 abril 2018. Datos: numeroteca.org",
       x = NULL,
       y = NULL,
       caption = "")

# converts to long format -----
names(results)
table(results$newspaper)

# porcentajes
results_long_per <- results[,c(1,25,13:18)] %>%
  gather(key, value, -newspaper, -date)
# numero de noticias
results_long_n <- results[,c(1,25,7:12)] %>%
  gather(key, value, -newspaper, -date)

# creates color palette
paltidos <- c("#7bb135", "#93336b", "#2a7db7", "#d01f1f", "#fa8619", "#999999")

# para un periodico -----
ggplot(data=results_long_n[results_long_n$newspaper=="eldiario",]) + #ylim(c(0,30)) +
  geom_line(aes(x=date, y=value, color=key),size=0.4) +
  geom_smooth(aes(x=date, y=value, color=key),size=1) +
  scale_x_datetime(date_breaks = "1 day", date_labels = "%d", 
                 limits = my_limit) +
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  scale_color_manual(values=paltidos) +
  labs(title = paste("eldiario.es: porcentaje noticias y nº noticias",word1_explain,"vs",word2_explain),
       subtitle = "12 marzo - 14 abril 2019. Datos: numeroteca.org",
       x = NULL,
       y = NULL,
       caption = "")

# para todos los periodicos -------
numeroteca's avatar
numeroteca committed
533
ggplot(data=results_long_per) + #%>% filter(key== "n_selected_news_3_VOXabscal" | key== "n_selected_news_2_VOXmay") ) + 
534
  geom_line(aes(x=date, y=value, color=key),size=0.1) +
numeroteca's avatar
numeroteca committed
535 536
  geom_smooth(aes(x=date, y=value, color=key),size=1,se = FALSE,span=0.6) + #,span=0.3
  scale_x_datetime(date_breaks = "2 day", date_labels = "%d", 
537 538 539
                   limits = my_limit) +
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  scale_color_manual(values=paltidos) +
numeroteca's avatar
numeroteca committed
540 541
  labs(title = paste("% de noticias en página de inicio"),
       subtitle = "1 abril - 24 abril 2019",
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
       x = NULL,
       y = NULL,
       caption = "Datos: HomePageX. numeroteca.org") +
  theme(
    panel.grid.minor.x = element_blank(),
    panel.grid.minor.y = element_blank(),
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank()
    # legend.position = "bottom",
    # axis.text.x = element_text(angle = 90, vjust = 0.4)
  ) +
  facet_wrap(~newspaper)


# para todos los partidos -------
numeroteca's avatar
numeroteca committed
557
ggplot(data=results_long_per) + 
558 559
  geom_line(aes(x=date, y=value, color=newspaper),size=0.2) +
  geom_smooth(aes(x=date, y=value, color=newspaper),size=1.3,se = FALSE) + #,span=0.3
numeroteca's avatar
numeroteca committed
560
  scale_x_datetime(date_breaks = "2 day", date_labels = "%d", 
561 562 563
                   limits = my_limit) +
  theme_minimal(base_family = "Roboto Condensed", base_size = 14) +
  scale_colour_brewer(palette = "Set2") +
numeroteca's avatar
numeroteca committed
564 565
  labs(title = paste("% de noticias en página de inicio"),
       subtitle = "1 abril - 24 abril 2019",
566 567 568 569 570 571 572 573 574 575 576 577 578
       x = NULL,
       y = NULL,
       caption = "Datos: HomePageX. numeroteca.org") +
  theme(
    panel.grid.minor.x = element_blank(),
    panel.grid.minor.y = element_blank(),
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_blank()
    # legend.position = "bottom",
    # axis.text.x = element_text(angle = 90, vjust = 0.4)
  ) +
  facet_wrap(~key)

numeroteca's avatar
numeroteca committed
579 580 581
# medias per day
results_long_n %>% 
  groups_by(date)
582 583


584
# --------  Analysis and comparision with Pageonex.com paper front pages data ---------
585 586 587 588 589 590 591 592 593 594
library("rjson")
# Get json from pageonex.com
json_file <- "http://pageonex.com/numeroteca/tfm-cifuentes/export.json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

# Create empty dataf rame
df <- data.frame(matrix( ncol = 10,nrow = length(json_data$dates)  ))
# fill dataframe with pageonex data
for (i in 1:length(json_data$dates)) {
  df[i,] <- data.frame(json_data$data[[i]])
595 596
}

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
# Make column and row names nicer 
colnames(df) <- json_data$media
colnames(df)[10] <- "media"
rownames(df) <- json_data$dates

# create variable with dates
df$date <- rownames(df)

library(reshape)
portadas <- melt(df, id=c("date"))
portadas$value <- portadas$value*100
portadas$date <- as.Date(portadas$date, "%Y-%m-%d")
class(portadas$date)

# Plot para varios periódico
ggplot(data=portadas) + 
  geom_line(aes(x=date, y=value, group=variable),color="#000000",size=0.2) +
  labs(title = "% portadas dedicada a escándalo Cifuentes en portada")

ggplot( data=portadas[portadas$variable=="media",],aes(x = date)) + 
  geom_bar(aes(weight = value)) +
  labs(title = "Media % portada dedicado a escándalo Cifuentes")

ggplot( data=portadas[!portadas$variable=="media",],aes(x = date)) + 
  geom_bar(aes(weight = value, fill=variable)) +
  labs(title = "% portada dedicado a escándalo Cifuentes")

ggplot( data=portadas[portadas$variable=="La Razón",],aes(x = date)) + 
  geom_bar(aes(weight = value)) +
  labs(title = "La Razón: % portada dedicado a escándalo Cifuentes")

ggplot( ) + 
  geom_bar(data=portadas[portadas$variable=="La Razón",], aes(x = timestamp,weight = value),fill="#A74a83") +
  geom_line(data=results[results$newspaper=="larazon",], aes(x=date, y=percent, group=newspaper),color="#e78ac3",size=0.7) +
  labs(title = "La Razón: % portada papel vs % noticias en digital dedicado a escándalo Cifuentes")

ggplot( ) + 
  geom_bar(data=portadas[portadas$variable=="El Pa",], aes(x = timestamp,weight = value),fill="#A74a83") +
  geom_line(data=results[results$newspaper=="larazon",], aes(x=date, y=percent, group=newspaper),color="#e78ac3",size=0.7) +
  labs(title = "La Razón: % portada papel vs % noticias en digital dedicado a escándalo Cifuentes")

ggplot( data=portadas,aes(x = variable) ) + 
  geom_bar(aes(weight = value/nrow(df))) +
  labs(title = "% dedicado a escándalo Cifuentes en portada") +
  coord_flip()
642

643 644 645 646
# Plot de la media
ggplot(data=portadas[portadas$variable=="media",]) + 
  geom_line(aes(x=date, y=value, group=variable),color="#000000",size=0.2) +
  labs(title = "% portadas dedicada a escándalo Cifuentes en portada")
647

648 649 650
portadas$timestamp <- as.POSIXlt( paste(portadas$date," ","00:00:00", sep = "" ))
summary(portadas)
class(portadas$timestamp)
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781


# Testing parsing news in different newspapers ---------------------------
# ------- eldiario.es ----------------------
# reads html and stores it
page <- read_html("data/http!www.eldiario.es!!!!@2018-04-06T23:01:07.888847+00:00.gz")

# gets all the text in article titles. All articles are in h2 except the comics.
titles <- page %>% html_nodes("article h2 a") %>% html_text() %>% data.frame()
colnames(titles) <- "title"
titles$title <- as.character(titles$title)

# total of articles with link
n_news <- nrow(titles) 

# select news that contain cerating word
select_news <- data.frame(titles[grepl(word, titles$title),])

# Results
# number of articles that contain words
n_select_news<- nrow(select_news)
# Percentage of articles that contain words
percent <- n_select_news / n_news * 100

# ------- elconfidencial ----------------------
# reads html and stores it
page <- read_html("data/http!www.elconfidencial.com!|!!!@2018-03-22T09:01:11.318750+00:00.gz")

# gets all the text in article titles. All articles are in h2 except the comics.
titles <- page %>% html_nodes("article h3 a") %>% html_text() %>% data.frame()
colnames(titles) <- "title"

# total of articles with link
n_news <- nrow(titles) 

# select news that contain cerating word
select_news <- data.frame(titles[grepl(word, titles$title),])

# Results
# number of articles that contain words
n_select_news<- nrow(select_news)
# Percentage of articles that contain words
percent <- n_select_news / n_news * 100

# ------- elmundo ----------------------
# reads html and stores it
pageelmundo <- read_html("eldiario/http!www.elmundo.es!!!!@2018-04-07T19:01:02.620498+00:00_formated.html") 

# gets all the text in article titles. All articles are in h2 except the comics.
titles <- pageelmundo %>% html_nodes("main article h3 a") %>% html_text() %>% data.frame() #TODO NO FUNCIONA
titles
colnames(titles) <- "title"

# total of articles with link
n_news <- nrow(titles) 

# select news that contain cerating word
select_news <- data.frame(titles[grepl(word, titles$title),])

# Results
# number of articles that contain words
n_select_news<- nrow(select_news)
# Percentage of articles that contain words
percent <- n_select_news / n_news * 100

# ------- elpais ----------------------
# reads html and stores it
pageelpais <- read_html("data/http!www.elpais.com!!!!@2017-07-04T13:51:08.133418+00:00.gz")

# gets all the text in article titles. All articles are in h2 except the comics.
titles <- pageelpais %>% html_nodes("article h2 a") %>% html_text() %>% data.frame() #TODO NO FUNCIONA
colnames(titles) <- "title"

# total of articles with link
n_news <- nrow(titles) 

# select news that contain cerating word
select_news <- data.frame(titles[grepl(word, titles$title),])

# Results
# number of articles that contain words
n_select_news<- nrow(select_news)
# Percentage of articles that contain words
percent <- n_select_news / n_news * 100

# ------- La Razón ----------------------
# reads html and stores it
pagelarazon <- read_html("data/http!www.larazon.es!|!!!@2018-03-30T07:01:03.998265+00:00.gz", to="UTF-8") #TODO correct encoding

# gets all the text in article titles. All articles are in h2 except the comics.
titles <- pagelarazon %>% html_nodes("article h2 a") %>% html_text() %>% data.frame() #TODO NO FUNCIONA
colnames(titles) <- "title"
titles

# total of articles with link
n_news <- nrow(titles) 

# select news that contain cerating word
select_news <- data.frame(titles[grepl(word, titles$title),])

# Results
# number of articles that contain words
n_select_news<- nrow(select_news)
# Percentage of articles that contain words
percent <- n_select_news / n_news * 100
# -------- La razón test ----------
# for (i in 1:nrow(selected)) {
#   if ( selected$newspaper[i] == "larazon") {
#   page <- read_html( paste("data/",selected$urls[i], sep = "") )
# 
#     titles <- page %>% html_nodes("article h2 a") %>% html_text() %>% data.frame()
# 
#   colnames(titles) <- "title"
#   # titles$title <- as.character(titles$title)
#   # total of articles with link
#   n_news <- nrow(titles)
#   print(paste("nº noticias:",n_news))
# 
#   # select news that contain cerating word
#   selected_news <- data.frame(titles[grepl(word, titles$title),])
#   print(selected_news)
#   # Results
#   # number of articles that contain words
#   n_selected_news<- nrow(selected_news)
#   print(n_selected_news)
#   print(paste("nº noticias Cifuentes:",n_selected_news))
#   # Percentage of articles that contain words
# 
#   print(paste("day:",selected$day[i],"hour:",selected$hour[i],selected$newspaper[i]))
#   }
# }