blob: 7866121ac472fa05b9954108859ee9ab68e31c84 [file] [log] [blame]
Marc Kupietz827a3c12019-09-18 22:09:33 +02001#!/usr/bin/env Rscript
2#
3# Plot frequency of alternative expressions or spellings variants over time
4#
5library(RKorAPClient)
6library(ggplot2)
7library(reshape2)
8library(plotly)
9library(htmlwidgets)
10
11alternativesOverTime <- function(alternatives, years, kco = new("KorAPConnection", verbose=TRUE)) {
12 df = data.frame(year=years)
13 vc = "textType = /Zeit.*/ & pubDate in"
14 urls <- data.frame()
15 for (v in alternatives) {
16 df[v] <- sapply(df$year, function(y) {
17 kqo <- corpusQuery(kco, query=v, vc=paste(vc, y))
18 urls <<- rbind(urls, data.frame(Variant=v, year=y, url=kqo@webUIRequestUrl))
19 kqo@totalResults
20 })
21 }
22 df$total <- apply(df[,alternatives], 1, sum)
23 df <- merge(melt(df, measure.vars = alternatives, value.name = "afreq", variable.name = "Variant"),
24 urls, by=c("Variant", "year"))
25 df$ci <- t(sapply(Map(prop.test, df$afreq, df$total), "[[","conf.int"))
26 df$share <- df$afreq / df$total
27 g <- ggplot(data = df, mapping = aes(x = year, y = share, color=Variant, fill=Variant)) +
28 geom_ribbon(aes(ymin=ci[, 1], ymax=ci[, 2], color=Variant, fill=Variant), alpha=.3, linetype=0) +
29 geom_line() +
30 geom_point() +
31 ggtitle(paste0(alternatives, collapse = " vs. ")) +
32 xlab("TIME") +
33 ylab(sprintf("Observed frequency ratio")) +
34 theme(axis.text.x = element_text(angle = 45, hjust = 1)) + scale_x_continuous(breaks=unique(df$year))
35 pp <- ggplotly(g, tooltip = c("x", "y"))
36 for (i in 1:length(alternatives)) {
37 vdata <- df[df$Variant==alternatives[i],]
38 pp$x$data[[2+i]]$customdata <- vdata$url
39 pp$x$data[[2+i]]$text <- sprintf("%s<br />absolute: %d / %d", pp$x$data[[2+i]]$text, vdata$afreq, vdata$total)
40 }
41 ppp <- onRender(pp, "function(el, x) { el.on('plotly_click', function(d) { var url=d.points[0].customdata; window.open(url, 'korap') })}")
42 print(ppp)
43 df
44}
45
46df <- alternativesOverTime(c('so "genannte.?"', '"sogenannte.?"'), (1995:2018))