blob: 26ae1238d4e5d88fbdb380354bb406c605c144cb [file] [log] [blame]
Marc Kupietzbb7d2322019-10-06 21:42:34 +02001
2#' Convert corpus frequency table to instances per million.
3#'
4#' Convenience function for converting frequency tables to instances per
5#' million.
6#'
7#' Given a table with columns \code{f}, \code{conf.low}, and \code{conf.high}, \code{ipm} ads a \code{column ipm}
8#' und multiplies conf.low and \code{conf.high} with 10^6.
9#'
10#' @param df table returned from \code{\link{frequencyQuery}}
11#'
12#' @return original table with additional column \code{ipm} and converted columns \code{conf.low} and \code{conf.high}
13#' @export
14#'
15#' @importFrom dplyr .data
16#'
17#' @examples
18#' new("KorAPConnection") %>% frequencyQuery("Test", paste0("pubDate in ", 2000:2002)) %>% ipm()
19ipm <- function(df) {
20 df %>%
21 mutate(ipm = .data$f * 10^6, conf.low = .data$conf.low * 10^6, conf.high = .data$conf.high * 10^6)
22}
23
Marc Kupietz95240e92019-11-27 18:19:04 +010024#' Convert query or vc strings to plot labels
25#'
26#' Converts a vector of query or vc strings to typically appropriate legend labels
27#' by clipping off prefixes and suffixes that are common to all query strings.
28#'
29#' @param data string or vector of query or vc definition strings
30#' @return string or vector of strings with clipped off common prefixes and suffixes
31#'
32#' @examples
33#' queryStringToLabel(paste("textType = /Zeit.*/ & pubDate in", c(2010:2019)))
34#' queryStringToLabel(c("[marmot/m=mood:subj]", "[marmot/m=mood:ind]"))
35#' queryStringToLabel(c("wegen dem [tt/p=NN]", "wegen des [tt/p=NN]"))
36#'
37#' @importFrom PTXQC lcpCount
38#' @importFrom PTXQC lcsCount
39#'
40#' @export
41queryStringToLabel <- function(data) {
42 leftCommon = lcpCount(data)
43 while (leftCommon > 0 && grepl("[[:alnum:]]", substring(data[1], leftCommon, leftCommon))) {
44 leftCommon <- leftCommon - 1
45 }
46 rightCommon = lcsCount(data)
47 while (rightCommon > 0 && grepl("[[:alnum:]]", substring(data[1], rightCommon, rightCommon))) {
48 rightCommon <- rightCommon - 1
49 }
50 substring(data, leftCommon + 1, nchar(data) - rightCommon)
51}
52
Marc Kupietzbb7d2322019-10-06 21:42:34 +020053
Marc Kupietz865760f2019-10-07 19:29:44 +020054## Mute notes: "Undefined global functions or variables:"
55globalVariables(c("conf.high", "conf.low", "onRender", "webUIRequestUrl"))
56
57
58#' Experimental: Plot frequency by year graphs with confidence intervals
Marc Kupietzd68f9712019-10-06 21:48:00 +020059#'
Marc Kupietz865760f2019-10-07 19:29:44 +020060#' Experimental convenience function for plotting typical frequency by year graphs with confidence intervals using ggplot2.
61#' \bold{Warning:} This function may be moved to a new package.
62#'
63#' @param mapping Set of aesthetic mappings created by aes() or aes_(). If specified and inherit.aes = TRUE (the default), it is combined with the default mapping at the top level of the plot. You must supply mapping if there is no plot mapping.
64#' @param ... Other arguments passed to geom_ribbon, geom_line, and geom_click_point.
Marc Kupietzd68f9712019-10-06 21:48:00 +020065#'
66#' @examples
67#' library(ggplot2)
68#' kco <- new("KorAPConnection", verbose=TRUE)
69#' expand_grid(condition = c("textDomain = /Wirtschaft.*/", "textDomain != /Wirtschaft.*/"),
70#' year = (2002:2018)) %>%
71#' cbind(frequencyQuery(kco, "[tt/l=Heuschrecke]",
72#' paste0(.$condition," & pubDate in ", .$year))) %>%
73#' ipm() %>%
Marc Kupietz865760f2019-10-07 19:29:44 +020074#' ggplot(aes(year, ipm, fill = condition, color = condition)) +
Marc Kupietzd68f9712019-10-06 21:48:00 +020075#' geom_freq_by_year_ci()
76#'
Marc Kupietz865760f2019-10-07 19:29:44 +020077#' @importFrom ggplot2 ggplot aes geom_ribbon geom_line geom_point theme element_text scale_x_continuous
Marc Kupietzd68f9712019-10-06 21:48:00 +020078#'
79#' @export
Marc Kupietz865760f2019-10-07 19:29:44 +020080geom_freq_by_year_ci <- function(mapping = aes(ymin=conf.low, ymax=conf.high), ...) {
Marc Kupietzd68f9712019-10-06 21:48:00 +020081 list(
Marc Kupietz865760f2019-10-07 19:29:44 +020082 geom_ribbon(mapping,
83 alpha = .3, linetype = 0, show.legend = FALSE, ...),
84 geom_line(...),
85 geom_click_point(aes(url=webUIRequestUrl), ...),
86 theme(axis.text.x = element_text(angle = 45, hjust = 1), legend.position = c(0.8, 0.2)),
Marc Kupietzd68f9712019-10-06 21:48:00 +020087 scale_x_continuous(breaks = function(x) seq(ceiling(x[1]), floor(x[2]), by = 1 + floor(((x[2]-x[1])/30)))))
88}
89
Marc Kupietz865760f2019-10-07 19:29:44 +020090#' @importFrom ggplot2 ggproto aes GeomPoint
91GeomClickPoint <- ggproto(
92 "GeomPoint",
93 GeomPoint,
94 required_aes = c("x", "y"),
95 default_aes = aes(
96 shape = 19, colour = "black", size = 1.5, fill = NA,
97 alpha = NA, stroke = 0.5, url = NA
98 ),
99 extra_params = c("na.rm", "url"),
100 draw_panel = function(data, panel_params,
101 coord, na.rm = FALSE, showpoints = TRUE, url = NULL) {
102 GeomPoint$draw_panel(data, panel_params, coord, na.rm = na.rm)
103 }
104)
105
106#' @importFrom ggplot2 layer
107geom_click_point <- function(mapping = NULL, data = NULL, stat = "identity",
108 position = "identity", na.rm = FALSE, show.legend = NA,
109 inherit.aes = TRUE, url = NA, ...) {
110 layer(
111 geom = GeomClickPoint, mapping = mapping, data = data, stat = stat,
112 position = position, show.legend = show.legend, inherit.aes = inherit.aes,
113 params = list(na.rm = na.rm, ...)
114 )
115}
116
117
118#' @importFrom htmlwidgets onRender
119tooltip2hyperlink <- function(p, attribute="webUIRequestUrl") {
120 pattern <- paste0(attribute, ": ([^<]+)")
121 for(i in grep(attribute, p$x$data)) {
122 x <- p[["x"]][["data"]][[i]][["text"]]
123 m <- regexpr(pattern, x)
124 matches <- sub(paste0(attribute, ": "), "", regmatches(x, m))
125 p$x$data[[i]]$customdata <- matches
126 p[["x"]][["data"]][[i]][["text"]] <- sub(paste0(attribute, ":[^<]*<br ?/?>"), "", p[["x"]][["data"]][[i]][["text"]] )
127 }
128 onRender(p, "function(el, x) { el.on('plotly_click', function(d) { var url=d.points[0].customdata; if(url) { window.open(url, 'korap') } })}")
129}
130
131#' Experimental: Convert ggplot2 to plotly with hyperlinks to KorAP queries
132#'
133#' \code{RKorAPClient::ggplotly} converts a \code{ggplot2::ggplot()} object to a plotly
134#' object with hyperlinks from data points to corresponding KorAP queries.
135#' \bold{Warning:} This function may be moved to a new package.
136#'
137#' @param p a ggplot object.
138#' @param tooltip a character vector specifying which aesthetic mappings to show
139#' in the tooltip. If you want hyperlinks to KorAP queries you need to include
140#' \code{"url"} here.
141#' @param ... Other arguments passed to \code{plotly::ggplotly}
142#'
143#' @examples
144#' library(ggplot2)
145#' kco <- new("KorAPConnection", verbose=TRUE)
146#' g <- expand_grid(condition = c("textDomain = /Wirtschaft.*/", "textDomain != /Wirtschaft.*/"),
147#' year = (2002:2018)) %>%
148#' cbind(frequencyQuery(kco, "[tt/l=Heuschrecke]",
149#' paste0(.$condition," & pubDate in ", .$year))) %>%
150#' ipm() %>%
151#' ggplot(aes(year, ipm, fill = condition, color = condition)) +
152#' ## theme_light(base_size = 20) +
153#' geom_freq_by_year_ci()
154#' p <- ggplotly(g)
155#' print(p)
156#' ## saveWidget(p, paste0(tmpdir(), "heuschrecke.html")
157#'
158#'
159#' @importFrom plotly ggplotly
160#' @importFrom htmlwidgets saveWidget
161#' @export
162ggplotly <- function(p = ggplot2::last_plot(), tooltip = c("x", "y", "colour", "url"), ...) {
163 pp <- plotly::ggplotly(p = p, tooltip = tooltip, ...)
164 tooltip2hyperlink(pp)
165}