# librerias
library(qdapRegex)
library(sentimentr)
library(syuzhet)
library(lubridate)
library(tidyverse)
library(tidytext)
library(forcats)
library(tokenizers)
library(widyr)
library(igraph)
library(ggraph)
library(topicmodels)
library(forcats)
library(scales)
library(stringr)
library(extrafont)
library(reldist)
library(grid)
library(gridExtra)
library(boot)
library(ggradar)
library(tidygraph)
library(boot)
# Sys.getenv()
Sys.setenv(JAVA_HOME = "C:\\Program Files\\Java\\jre1.8.0_251")
library(tm)
library(qdap)
# funciones auxiliares
source(here::here("scripts", "funciones_auxiliares.R"))
# paleta
plots_palette <- c("#ad5d51", "grey55", "#2b559e", "#947240")
# orden comunidades
comunidad_order <- c("GOP", "Independent", "DNC", "Progressives")
Carga de datos. Estos datos han sido previamente procesados, sobre todo en lo que se refiere al texto de los tweets. Se excluyen términos relacionados con la pandemia que provoca la enfermedad COVID-19 (en el texto sin limpiar, hay un número amplio de términos para referirse a la enfermedad. Se han unificado todos en el término COVID19).
Se ha recogido también información sobre los seguidores de cuentas para definir 4 comunidades
climate <- readRDS(here::here("datos_procesados", "formated_text_df_data", "climatechange.rds")) %>%
filter(str_detect(text, "#?covid19|#?COVID|#?[Pp]andemic|#chinavirus|#wuhanvirus", negate = T)) %>%
mutate(comunidad = fct_relevel(comunidad, c("GOP", "Independent", "DNC", "Progressives")))
climate %>%
count(comunidad) %>%
mutate(Porcentaje = percent(n /sum(n), accuracy = 0.1))
## # A tibble: 4 x 3
## comunidad n Porcentaje
## <fct> <int> <chr>
## 1 GOP 5893 6.9%
## 2 Independent 69013 80.5%
## 3 DNC 5000 5.8%
## 4 Progressives 5838 6.8%
# sentimiento
freq_tweets_usuario <- get_tweet_distribution(climate)
# Curva de lorenz
freq_tweets_usuario %>%
ggplot(aes(x = porc_usuarios_acum, y = porc_tweets_acum)) +
geom_line(aes(color = comunidad), size = 1.3) +
scale_color_manual(values = plots_palette) +
labs(x = "% acumulado de usuarios", y = "% Acumulado de tweets",
title = "Curva de Lorenz para el nº de usarios y el nº de tweets") +
scale_x_continuous(labels = scales::percent) +
scale_y_continuous(labels = scales::percent) +
theme_bw() +
theme(text = element_text(family = "Georgia", color = "grey45"),
legend.title = element_blank())
# gini
gini_comunidades <- freq_tweets_usuario %>%
group_by(comunidad) %>%
summarise(gini = gini(x = tweets, weights = porc_usuarios)) %>%
arrange(desc(gini))
La referencia distintiva de cabecera para el GOP es BribeBart News. Un medio conservador, que tuvo como director a Steve Bannon.
La mención más destacada en el partido demócrata es (Rick Wilson)[http://www.therickwilson.com/about/] , estratega político asociado al (Lincoln Project)[https://lincolnproject.us/], un movimiento republicano anti Donald Trump
climate_tfidf_mentions <- get_tfidf(climate_unigram %>% filter(str_detect(word, "^@"),comunidad!= "Independent") %>% get_frequencies())
plot_tfidf(climate_tfidf_mentions, cols = 3, colores = c(1, 3, 4)) +
labs(title = "Tópicos característicos de cada comunidad", y = "TF-IDF") +
guides(fill = F) +
theme(axis.title.x= element_blank(),
axis.text.y = element_text(size = 16),
legend.title = element_blank(),
strip.text = element_text(size = 15))
# climatechangte
nrc_climate <- climate_unigram %>%
filter(comunidad!= "Independent") %>%
inner_join(get_sentiments("nrc"), by = "word") %>%
filter(!sentiment %in% c("positive", "negative")) %>%
count(comunidad, sentiment, sort = T) %>%
mutate(sentiment = str_to_title(sentiment)) %>%
ungroup() %>%
group_by(comunidad) %>%
mutate(n = rescale(n)) %>%
pivot_wider(names_from = sentiment, values_from = n) %>%
select(comunidad, Joy, Trust, Fear, Surprise, Sadness, Disgust, Anger, Anticipation, Joy)
# predomina miedo
ggradar(nrc_climate %>% ungroup() %>% mutate(comunidad = fct_drop(comunidad)), group.colours = plots_palette[c(1, 3, 4)], legend.position = "top",
group.point.size = 4,
plot.title = "Sentimientos expresados hacia el tópico 'Climate Change'", legend.text.size = 11) +
theme(plot.title = element_text(size = 12, family = "Georgia", color = "grey55"),
axis.title = element_text(family = "Georgia"))
Sorporendentemente los tres grupos dan una valoración positiva.
# he filtrado fuera temas algunos temas políticos porque hay demasiada ironía
green_sent <- readRDS(here::here("datos_procesados", "formated_sent_df_data", "greennewdeal_sent.rds")) %>%
filter(str_detect(text, "#?covid19|#?COVID|#?[Pp]andemic|#chinavirus|#wuhamvirus", negate = T))
green_sent %>%
filter(!is_retweet) %>%
group_by(comunidad) %>%
summarise(sent = mean(ave_sentiment),
n = n())
## # A tibble: 3 x 3
## comunidad sent n
## <chr> <dbl> <int>
## 1 DNC 0.227 251
## 2 GOP 0.187 841
## 3 Progressives 0.253 1276
En este caso, en el partido republicano hay un número significativo de tweets irónicos, con lo que este tipo de análisis queda invalidado
green_sent %>%
filter(status_id == "1260399668594454531") %>% .$text
## [1] "@rooticusprime @sadieisrael @gatewaypundit only leftist approved thought i am sure we will learn to love our green new deal and spout that aoc is a genius project dragonfly was for us not china"
Esto es parecido al grafico de red al lado de las barras, pero ahor midiendo directamente la correlación entre los hashtags con el coeficiente phi. puede que sustituya al grafico de red de arriba.
gop_cor_net <- get_correlation_network(climate_hashtag, climate_frequency, com = "GOP", exclude_words = "#greennewdeal", cor_limit = 0.2) %>%
activate(nodes) %>% mutate(comunidad = "GOP")
dnc_cor_net <- get_correlation_network(climate_hashtag, climate_frequency, com = "DNC", exclude_words = "#greennewdeal", cor_limit = 0.2) %>%
activate(nodes) %>% mutate(comunidad = "DNC")
prg_cor_net <- get_correlation_network(climate_hashtag, climate_frequency, com = "Progressives", exclude_words = "#greennewdeal", cor_limit = 0.2) %>%
activate(nodes) %>% mutate(comunidad = "Progressives")
climate_net <- bind_graphs(gop_cor_net, dnc_cor_net, prg_cor_net) %>%
activate(nodes) %>%
mutate(comunidad = fct_relevel(comunidad, c("GOP", "DNC", "Progressives")))
climate_net %>%
ggraph(layout = "fr") +
geom_edge_link(aes(edge_alpha = correlation), show.legend = FALSE) +
geom_node_point(pch = 21, aes(fill = sent, size = n)) +
geom_node_text( aes(label = name, color = comunidad), repel = TRUE, size = 3) +
facet_nodes(~comunidad, ncol = 1, scales = "free") +
scale_fill_gradient2(low = "red", high = "green", mid = "grey") +
scale_color_manual(values = plots_palette[c(1, 3, 4)]) +
facet_nodes(~comunidad, ncol = 1, scales = "free") +
theme_graph() +
guides(color = F) +
theme(strip.text = element_text(size = 16))
# gop_cor_net <- ggplotGrob(plot_correlation_network(climate_hashtag, climate_frequency, com = "GOP", exclude_words = "#greennewdeal",
# text_size = 2, point_size = 2, text_color = plots_palette[1]))
# dnc_cor_net <- ggplotGrob(plot_correlation_network(climate_hashtag, climate_frequency, com = "DNC", exclude_words = "#greennewdeal",
# text_size = 2, point_size = 2, text_color = plots_palette[3]))
# prg_cor_net <- ggplotGrob(plot_correlation_network(climate_hashtag, climate_frequency, com = "Progressives", exclude_words = "#greennewdeal",
# text_size = 2, point_size = 2, text_color = plots_palette[4]))
# grid.arrange(gop_cor_net, dnc_cor_net, prg_cor_net, ncol = 1)
Niveles inexistentes de polarización al comparar las comunidades
library(boot)
pol_test_dif <- readRDS(here::here("datos_procesados", "formated_polarization_df_data", "polarization_testing", "climatechange_polarization.rds"))
pol_test_dif[-1]
## $IC
## 2.5% 97.5%
## DNC-GOP 0.02083333 0.07886905
## DNC-PRG 0.02083333 0.07916667
##
## $resultado
## [1] "No se encuentran diferencias en medias"
pol_test_dif$data %>%
ggplot(aes(x = sentimiento)) +
geom_histogram(aes(group = comunidad, fill = comunidad), color = "white", alpha = 0.5, binwidth = 0.002, position = "identity") +
scale_fill_manual(values = plots_palette[c(1, 4)]) +
labs(x = "Average polarization score", title = "Replicaciones bootstrap del scoring medio de polarización")