blob: 2b9a557a0349eb478547071effb3e28253f1f04e [file] [log] [blame]
Marc Kupietz91145b02020-01-29 15:58:36 +01001#' Experimental: Plot interactive frequency by year graphs with confidence intervals using highcharter
2#'
3#' Experimental convenience function for plotting typical frequency by year graphs with confidence intervals using highcharter.
4#' \bold{Warning:} This function may be moved to a new package.
5#'
6#' @import highcharter
Marc Kupietzb7e7f722020-06-02 12:29:18 +02007#' @importFrom tibble add_column
Marc Kupietz91145b02020-01-29 15:58:36 +01008#' @export
9#'
10#' @param df data frame like the value of a \code{\link{frequencyQuery}}
Marc Kupietz43a6ade2020-02-18 17:01:44 +010011#' @param as.alternatives boolean decides whether queries should be treated as mutually exclusive and exhaustive wrt. to some meaningful class (e.g. spelling variants of a certain word form).
Marc Kupietz91145b02020-01-29 15:58:36 +010012#' @param ylabel defaults to \% if \code{as.alternatives} is \code{true} and to "ipm" otherwise.
Marc Kupietzab0b0712020-05-04 16:24:57 +020013#' @param smooth boolean decides whether the graph is smoothed using the highcharts plot types spline and areasplinerange.
Marc Kupietz5b503f42020-04-09 15:26:00 +020014#' @param ... additional arguments passed to \code{\link{hc_add_series}}
Marc Kupietz91145b02020-01-29 15:58:36 +010015#'
16#' @examples
Marc Kupietz657d8e72020-02-25 18:31:50 +010017#' \donttest{year <- c(1990:2018)}\dontshow{year <- c(2013:2013)}
18#' \donttest{alternatives <- c("macht []{0,3} Sinn", "ergibt []{0,3} Sinn")}\dontshow{alternatives <- c("macht []{0,3} Sinn")}
Marc Kupietz91145b02020-01-29 15:58:36 +010019#' new("KorAPConnection", verbose = TRUE) %>%
Marc Kupietz657d8e72020-02-25 18:31:50 +010020#' frequencyQuery(query = alternatives,
Marc Kupietz05b22772020-02-18 21:58:42 +010021#' vc = paste("textType = /Zeit.*/ & pubDate in", year),
Marc Kupietz91145b02020-01-29 15:58:36 +010022#' as.alternatives = TRUE) %>%
23#' hc_freq_by_year_ci(as.alternatives = TRUE)
24#'
Marc Kupietz05b22772020-02-18 21:58:42 +010025#' \donttest{
Marc Kupietz10f65c42020-01-31 15:18:24 +010026#' kco <- new("KorAPConnection", verbose = TRUE)
27#' expand_grid(
28#' condition = c("textDomain = /Wirtschaft.*/", "textDomain != /Wirtschaft.*/"),
29#' year = (2005:2011)
30#' ) %>%
31#' cbind(frequencyQuery(
32#' kco,
33#' "[tt/l=Heuschrecke]",
34#' paste0(.$condition, " & pubDate in ", .$year)
35#' )) %>%
36#' hc_freq_by_year_ci()
Marc Kupietz05b22772020-02-18 21:58:42 +010037#' }
Marc Kupietz10f65c42020-01-31 15:18:24 +010038#'
Marc Kupietzab0b0712020-05-04 16:24:57 +020039hc_freq_by_year_ci <- function(df, as.alternatives = FALSE,
40 ylabel = if(as.alternatives) "%" else "ipm",
41 smooth = FALSE,
42 ...) {
Marc Kupietz91145b02020-01-29 15:58:36 +010043 title <- ""
44 df <- df %>%
45 { if(! as.alternatives) ipm(.) else RKorAPClient::percent(.) }
46
47 if (!"year" %in% colnames(df)) {
Marc Kupietzb7e7f722020-06-02 12:29:18 +020048 df <- df %>% add_column(year = as.integer(queryStringToLabel(df$vc, pubDateOnly = TRUE)))
Marc Kupietz91145b02020-01-29 15:58:36 +010049 }
50 if (!"condition" %in% colnames(df)) {
51 if (length(base::unique(df$query)) > 1) {
52 df <- df %>% mutate(condition = query)
Marc Kupietzcf1771d2020-03-04 16:03:04 +010053 if(length(base::unique(queryStringToLabel(df$vc, excludePubDate = TRUE ))) > 1) {
Marc Kupietz91145b02020-01-29 15:58:36 +010054 df <- df %>% mutate(condition = paste(condition, " & ",
Marc Kupietzcf1771d2020-03-04 16:03:04 +010055 queryStringToLabel(vc, excludePubDate = TRUE )))
Marc Kupietz91145b02020-01-29 15:58:36 +010056 }
57 } else {
Marc Kupietz5d70ffe2020-03-12 11:16:43 +010058 if (length(base::unique(queryStringToLabel(df$vc, excludePubDate = TRUE ))) > 1) {
59 title <- base::unique(df$query)
Marc Kupietzb7e7f722020-06-02 12:29:18 +020060 df <- df %>% add_column(condition = queryStringToLabel(vc, excludePubDate = TRUE ))
Marc Kupietz5d70ffe2020-03-12 11:16:43 +010061 } else {
62 df <- df %>% mutate(condition = query)
Marc Kupietz91145b02020-01-29 15:58:36 +010063 }
64 }
65 }
66 # use the D3 palette which provides 20 attractive and distinguishable colours
67 palette <- c("#1F77B4", "#FF7F0E", "#2CA02C", "#D62728", "#9467BD", "#8C564B", "#E377C2", "#7F7F7F", "#BCBD22", "#17BECF", "#AEC7E8", "#FFBB78", "#98DF8A", "#FF9896", "#C5B0D5", "#C49C94", "#F7B6D2", "#C7C7C7", "#DBDB8D", "#9EDAE5")
68 highcharter::highchart() %>%
69 hc_title(text=title) %>%
Marc Kupietz91145b02020-01-29 15:58:36 +010070 hc_yAxis(
71 title = list(text = if (as.alternatives) "" else ylabel),
72 ceiling = if (as.alternatives) 100 else NULL,
73 floor = 0,
74 labels = if(as.alternatives) list(format = paste0("{value}\U2009", ylabel)) else NULL
75 ) %>%
Marc Kupietzcf1771d2020-03-04 16:03:04 +010076 hc_xAxis(allowDecimals=FALSE) %>%
Marc Kupietz91145b02020-01-29 15:58:36 +010077 hc_add_theme(hc_theme_google(colors=palette)) %>%
Marc Kupietze2038322021-03-04 18:24:02 +010078 hc_add_onclick_korap_search() %>%
Marc Kupietzcf1771d2020-03-04 16:03:04 +010079 hc_credits(enabled = TRUE,
Marc Kupietz900d0522020-03-19 13:36:45 +010080 text = "KorAP R Client Package",
81 href = "https://github.com/KorAP/RKorAPClient/") %>%
Marc Kupietzcf1771d2020-03-04 16:03:04 +010082 hc_exporting(enabled = TRUE) %>%
Marc Kupietz91145b02020-01-29 15:58:36 +010083 hc_tooltip(
Marc Kupietzab0b0712020-05-04 16:24:57 +020084 headerFormat = '<span style="font-size: 10pt">{point.key}</span><br/>',
Marc Kupietz91145b02020-01-29 15:58:36 +010085 formatter = JS(paste0("function (tooltip) {
86 var str = tooltip.defaultFormatter.call(this, tooltip);
87 if(Array.isArray(str)) {
88 str = str.join('');
89 }
90 for (var i = 0; i < this.points.length; i++) {
91 str = str.replace(/([0-9.,]+.?)", ylabel, "/, this.points[i].point.count+' ($1@)');
92 }
93 return str.replace(/@/g, '", ylabel, "')
94 } ")),
Marc Kupietzcf1771d2020-03-04 16:03:04 +010095 crosshairs = TRUE,
Marc Kupietz91145b02020-01-29 15:58:36 +010096 valueDecimals = 2,
Marc Kupietzcf1771d2020-03-04 16:03:04 +010097 shared = TRUE,
Marc Kupietz91145b02020-01-29 15:58:36 +010098 valueSuffix = paste0('\U2009', ylabel)
99 ) %>%
Marc Kupietzab0b0712020-05-04 16:24:57 +0200100 hc_add_series_korap_frequencies(df, smooth, as.alternatives, ...)
Marc Kupietz91145b02020-01-29 15:58:36 +0100101}
102
Marc Kupietza4f36532020-02-03 22:50:08 +0100103## Mute notes: "no visible binding for global variable:"
104globalVariables(c("value", "query", "condition", "vc"))
105
Marc Kupietzab0b0712020-05-04 16:24:57 +0200106hc_add_series_korap_frequencies <- function(hc, df, smooth = FALSE,
107 as.alternatives = FALSE,
108 ...) {
Marc Kupietz91145b02020-01-29 15:58:36 +0100109 index <- 0
Marc Kupietzab0b0712020-05-04 16:24:57 +0200110 type <- ifelse(smooth, "spline", "line")
111 areatype <- ifelse(smooth, "areasplinerange", "arearange")
Marc Kupietz91145b02020-01-29 15:58:36 +0100112 for(q in unique(df$condition)) {
113 dat <- df[df$condition==q,]
114 hc <- hc %>% hc_add_series(
115 marker = list(radius = 2),
116 name = q,
117 data = data.frame(
118 year = dat$year,
119 value = if (as.alternatives) dat$f else dat$ipm,
120 count = dat$totalResults,
Marc Kupietze2038322021-03-04 18:24:02 +0100121 webUIRequestUrl = dat$webUIRequestUrl
Marc Kupietz91145b02020-01-29 15:58:36 +0100122 ),
123 hcaes(year, value),
Marc Kupietzab0b0712020-05-04 16:24:57 +0200124 type = type,
Marc Kupietz91145b02020-01-29 15:58:36 +0100125 colorIndex = index,
Marc Kupietz5b503f42020-04-09 15:26:00 +0200126 zIndex = 1,
127 ...
Marc Kupietz91145b02020-01-29 15:58:36 +0100128 ) %>%
129 hc_add_series(
130 name = "ci",
131 data = dat[,c('year', 'conf.low', 'conf.high')],
132 hcaes(x = year, low = conf.low, high = conf.high),
Marc Kupietzab0b0712020-05-04 16:24:57 +0200133 type = areatype,
Marc Kupietz91145b02020-01-29 15:58:36 +0100134 fillOpacity = 0.3,
135 lineWidth = 0,
Marc Kupietzcf1771d2020-03-04 16:03:04 +0100136 marker = list(enabled = FALSE),
137 enableMouseTracking = FALSE,
Marc Kupietz91145b02020-01-29 15:58:36 +0100138 linkedTo= ':previous',
139 colorIndex = index,
140 zIndex = 0
141 )
142 index <- index+1
143 }
144 hc
145}
Marc Kupietz882f08c2020-03-18 13:30:31 +0100146
Marc Kupietze2038322021-03-04 18:24:02 +0100147#' Add KorAP search click events to highchart
148#'
149#' @description
150#' Adds on-click events to data points of highcarts that were constructed with
151#' \ref{frequencyQuery} or ref \ref{collocationScoreQuery}. Clicks on data points
152#' then launch KorAP web UI queries for the given query term and virtual corpus in
153#' a separate frame.
154#'
155#' @param hc highchart
156#'
157#' @export
158#'
159#' @examples
160#' \donttest{
161#' library(highcharter)
162#' library(tidyr)
163#'
164#' new("KorAPConnection", verbose = TRUE) %>%
165#' collocationScoreQuery("Team", "agil", vc = paste("pubDate in", c(2014:2018)),
166#' lemmatizeNodeQuery = TRUE, lemmatizeCollocateQuery = TRUE) %>%
167#' pivot_longer(c("O", "E")) %>%
168#' hchart(type="spline", hcaes(label, value, group=name)) %>%
169#' hc_add_onclick_korap_search()
170#' }
171#'
172hc_add_onclick_korap_search <- function(hc) {
173 hc_plotOptions(
174 hc,
175 series = list(enabled = TRUE),
176 spline = list(cursor = 'pointer', point = list(events = list(
177 click = JS("function() { window.open(this.webUIRequestUrl, 'korap'); }")
178 ))),
179 line = list(cursor = 'pointer', point = list(events = list(
180 click = JS("function() { window.open(this.webUIRequestUrl, 'korap'); }")
181 ))))
182}
183
Marc Kupietz882f08c2020-03-18 13:30:31 +0100184.onAttach <- function(libname = find.package("RKorAPClient"),
185 pkgname = "RKorAPClient") {
186 packageStartupMessage(
187 "If you intend to use the Highcharts plot options, please note that Highcharts (www.highcharts.com) is a Highsoft software product which is not free for commercial and governmental use."
188 )
189}
190