├── .github ├── .gitignore └── workflows │ ├── R-CMD-check.yaml │ └── test-coverage.yaml ├── tests ├── .gitignore ├── testthat │ ├── .gitignore │ ├── test-utils.R │ ├── test-default-methods.R │ ├── test-textplot_keyness.R │ ├── test-textplot_scale1d.R │ ├── test-textplot_wordcloud.R │ ├── test-textplot_network.R │ └── test-textplot_xray.R ├── spelling.R ├── testthat.R └── data │ └── stjohn_latin.csv ├── .lintr ├── cran-comments.md ├── .gitignore ├── .Rbuildignore ├── R ├── RcppExports.R ├── quanteda.textplots-package.R ├── utils.R ├── textplot_keyness.R ├── textplot_xray.R ├── textplot_network.R ├── textplot_scale1d.R └── textplot_wordcloud.R ├── codecov.yml ├── inst ├── WORDLIST └── CITATION ├── man ├── as.igraph.Rd ├── as.network.Rd ├── check_font.Rd ├── quanteda.textplots-package.Rd ├── textplot_xray.Rd ├── wordcloud_comparison.Rd ├── wordcloud.Rd ├── textplot_keyness.Rd ├── textplot_network.Rd ├── textplot_scale1d.Rd └── textplot_wordcloud.Rd ├── src ├── wordcloud.cpp └── RcppExports.cpp ├── NEWS.md ├── CONDUCT.md ├── DESCRIPTION ├── NAMESPACE ├── README.md ├── README.Rmd └── LICENSE /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /tests/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /tests/testthat/.gitignore: -------------------------------------------------------------------------------- 1 | Rplots*.pdf 2 | -------------------------------------------------------------------------------- /.lintr: -------------------------------------------------------------------------------- 1 | linters: with_defaults(line_length_linter(100)) 2 | -------------------------------------------------------------------------------- /tests/spelling.R: -------------------------------------------------------------------------------- 1 | if (requireNamespace("spelling", quietly = TRUE)) 2 | spelling::spell_check_test(vignettes = TRUE, error = TRUE, skip_on_cran = TRUE) 3 | -------------------------------------------------------------------------------- /cran-comments.md: -------------------------------------------------------------------------------- 1 | # Submission notes 2 | 3 | * Replaces a deprecated argument in ggplot, to avoid a deprecation warning. 4 | * Updates GitHub actions for more modern checks. 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | src/*.o 6 | src/*.so 7 | src/*.dll 8 | .DS_Store 9 | R/.DS_Store 10 | quanteda.textplots.Rproj 11 | revdep 12 | -------------------------------------------------------------------------------- /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^CONDUCT\.md$ 4 | ^README\.Rmd$ 5 | ^cran-comments.md$ 6 | ^LICENSE$ 7 | ^\.github$ 8 | ^\.lintr$ 9 | ^CRAN-RELEASE$ 10 | ^revdep$ 11 | ^CRAN-SUBMISSION$ 12 | ^codecov\.yml$ 13 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | qatd_cpp_is_overlap <- function(x1_, y1_, w1_, h1_, boxe_) { 5 | .Call(`_quanteda_textplots_qatd_cpp_is_overlap`, x1_, y1_, w1_, h1_, boxe_) 6 | } 7 | 8 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | comment: false 2 | 3 | coverage: 4 | status: 5 | project: 6 | default: 7 | target: auto 8 | threshold: 1% 9 | informational: true 10 | patch: 11 | default: 12 | target: auto 13 | threshold: 1% 14 | informational: true 15 | -------------------------------------------------------------------------------- /inst/WORDLIST: -------------------------------------------------------------------------------- 1 | CMD 2 | Codecov 3 | ERC 4 | Fellows's 5 | NOTEs 6 | Nulty 7 | ORCID 8 | QUANTESS 9 | StG 10 | StackOverflow 11 | codecov 12 | color 13 | dfm 14 | docnames 15 | docvars 16 | extrafont 17 | fcm 18 | igraph 19 | keyness 20 | kwic 21 | overplot 22 | quanteda 23 | textplot 24 | textplots 25 | th 26 | wordcloud 27 | -------------------------------------------------------------------------------- /R/quanteda.textplots-package.R: -------------------------------------------------------------------------------- 1 | #' @keywords internal 2 | #' @importFrom Rcpp evalCpp 3 | #' @useDynLib "quanteda.textplots", .registration = TRUE 4 | "_PACKAGE" 5 | 6 | # The following block is used by usethis to automatically manage 7 | # roxygen namespace tags. Modify with care! 8 | ## usethis namespace: start 9 | ## usethis namespace: end 10 | NULL 11 | -------------------------------------------------------------------------------- /man/as.igraph.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_network.R 3 | \name{as.igraph} 4 | \alias{as.igraph} 5 | \title{Convert an fcm to an igraph object} 6 | \usage{ 7 | as.igraph(x, ...) 8 | } 9 | \description{ 10 | Convert an \link[quanteda:fcm]{fcm} object to an \pkg{igraph} graph object. 11 | } 12 | \keyword{internal} 13 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | Sys.setenv("R_TESTS" = "") 2 | Sys.setenv("_R_CHECK_LENGTH_1_CONDITION_" = TRUE) 3 | 4 | library("testthat") 5 | library("quanteda") 6 | # library("quanteda.textmodels") 7 | library("quanteda.textplots") 8 | quanteda_options(reset = TRUE) 9 | 10 | # Error on Matrix deprecations 11 | options(Matrix.warnDeprecatedCoerce = 2) 12 | 13 | test_check("quanteda.textplots") 14 | -------------------------------------------------------------------------------- /man/as.network.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_network.R 3 | \name{as.network} 4 | \alias{as.network} 5 | \title{redefinition of network::as.network()} 6 | \usage{ 7 | as.network(x, ...) 8 | } 9 | \arguments{ 10 | \item{x}{input object} 11 | 12 | \item{...}{additional arguments} 13 | } 14 | \description{ 15 | redefinition of network::as.network() 16 | } 17 | \keyword{internal} 18 | -------------------------------------------------------------------------------- /tests/testthat/test-utils.R: -------------------------------------------------------------------------------- 1 | test_that("check_font is working", { 2 | skip_on_cran() 3 | # check_font no longer validates fonts, just passes them through 4 | expect_equal(quanteda.textplots:::check_font("XXXXX"), "XXXXX") 5 | expect_equal(quanteda.textplots:::check_font("sans"), "sans") 6 | expect_equal(quanteda.textplots:::check_font("serif"), "serif") 7 | expect_equal(quanteda.textplots:::check_font("mono"), "mono") 8 | expect_equal(quanteda.textplots:::check_font(NULL), "") 9 | }) 10 | -------------------------------------------------------------------------------- /man/check_font.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{check_font} 4 | \alias{check_font} 5 | \title{Prepare font parameter for plotting} 6 | \usage{ 7 | check_font(font) 8 | } 9 | \arguments{ 10 | \item{font}{name of a font to be used in plotting.} 11 | } 12 | \value{ 13 | character string 14 | } 15 | \description{ 16 | This function prepares font parameter for use with \pkg{ggplot2} and 17 | \pkg{graphics} APIs. No validation is performed - fonts are passed through 18 | and any invalid fonts will be handled by the graphics system. 19 | } 20 | \keyword{internal} 21 | -------------------------------------------------------------------------------- /tests/testthat/test-default-methods.R: -------------------------------------------------------------------------------- 1 | test_that("test default textplot methods", { 2 | expect_error( 3 | textplot_keyness(TRUE), 4 | "textplot_keyness\\(\\) only works on keyness objects" 5 | ) 6 | expect_error( 7 | textplot_wordcloud(TRUE), 8 | "textplot_wordcloud\\(\\) only works on dfm, keyness objects" 9 | ) 10 | expect_error( 11 | textplot_xray(TRUE), 12 | "textplot_xray\\(\\) only works on kwic objects" 13 | ) 14 | expect_error( 15 | textplot_scale1d(TRUE), 16 | "textplot_scale1d\\(\\) only works on predict.textmodel_wordscores, textmodel_ca, textmodel_wordfish, textmodel_wordscores objects" 17 | ) 18 | }) 19 | -------------------------------------------------------------------------------- /R/utils.R: -------------------------------------------------------------------------------- 1 | unused_dots <- quanteda:::unused_dots 2 | 3 | friendly_class_undefined_message <- quanteda:::friendly_class_undefined_message 4 | 5 | message_error <- quanteda:::message_error 6 | 7 | #' Prepare font parameter for plotting 8 | #' 9 | #' This function prepares font parameter for use with \pkg{ggplot2} and 10 | #' \pkg{graphics} APIs. No validation is performed - fonts are passed through 11 | #' and any invalid fonts will be handled by the graphics system. 12 | #' @param font name of a font to be used in plotting. 13 | #' @return character string 14 | #' @keywords internal 15 | check_font <- function(font) { 16 | if (is.null(font)) { 17 | font <- "" 18 | } 19 | return(font) 20 | } 21 | -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | if (!exists("meta") || is.null(meta)) 2 | meta <- packageDescription("quanteda") 3 | note <- sprintf("R package version %s", meta$Version) 4 | 5 | bibentry(bibtype = "article", 6 | title = "quanteda: An R package for the quantitative analysis of textual data", 7 | journal = "Journal of Open Source Software", 8 | author = c(person("Kenneth", "Benoit"), 9 | person("Kohei", "Watanabe"), 10 | person("Haiyan", "Wang"), 11 | person("Paul", "Nulty"), 12 | person("Adam", "Obeng"), 13 | person("Stefan", "Müller"), 14 | person("Akitaka", "Matsuo")), 15 | doi = "10.21105/joss.00774", 16 | url = "https://quanteda.io", 17 | volume = 3, 18 | number = 30, 19 | pages = 774, 20 | year = 2018 21 | ) 22 | -------------------------------------------------------------------------------- /src/wordcloud.cpp: -------------------------------------------------------------------------------- 1 | #include "Rcpp.h" 2 | using namespace Rcpp; 3 | 4 | /* 5 | * Detect if a box at position (x1_,y1_), with width w1_ and height h1_ overlaps 6 | * with any of the boxes in boxe_ 7 | */ 8 | 9 | // [[Rcpp::export]] 10 | bool qatd_cpp_is_overlap(SEXP x1_, SEXP y1_, SEXP w1_, SEXP h1_, SEXP boxe_) { 11 | 12 | double x1 = as(x1_); 13 | double y1 = as(y1_); 14 | double sw1 = as(w1_); 15 | double sh1 = as(h1_); 16 | Rcpp::List boxes(boxe_); 17 | Rcpp::NumericVector box_; 18 | double x2, y2, w2, h2; 19 | bool overlap= true; 20 | for (int i = 0; i < boxes.size(); i++) { 21 | box_ = boxes[i]; 22 | x2 = box_[0]; 23 | y2 = box_[1]; 24 | w2 = box_[2]; 25 | h2 = box_[3]; 26 | if (x1 < x2) { 27 | overlap = (x1 + sw1) > x2; 28 | } else { 29 | overlap = (x2 + w2) > x1; 30 | } 31 | if (y1 < y2) { 32 | overlap = (overlap && ((y1 + sh1) > y2)); 33 | } else { 34 | overlap = (overlap && ((y2 + h2) > y1)); 35 | } 36 | if(overlap) 37 | return true; 38 | } 39 | return false; 40 | } 41 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | # quanteda.textplots 0.96 2 | 3 | * Removes the dependency on **extrafont**, which was scheduled for archiving due to an unfixed failure of one of its reverse dependencies. 4 | 5 | # quanteda.textplots 0.95 6 | 7 | * Trims the C++ legacy compiler directives that are no longer needed, and were causing problems with the checks on CRAN. 8 | * Removed broken Rd links causing problems with the checks on CRAN. 9 | 10 | # quanteda.textplots 0.94.2 - 0.94.4 11 | 12 | * Updates to maintain clean CRAN checks and to ensure consistency with minor changes in underlying packages. 13 | 14 | 15 | # quanteda.textplots 0.94.1 16 | 17 | * Test update for changes in upcoming Matrix 1.4-1. 18 | 19 | # quanteda.textplots 0.94 20 | 21 | * Further updates in preparation for quanteda v3. 22 | 23 | # quanteda.textplots 0.93 24 | 25 | * Updates fcm and kwic plot methods for quanteda v3. 26 | * Removes dependency on data.table. 27 | 28 | # quanteda.textplots 0.91 29 | 30 | * Fixes some CRAN NOTEs caused by Namespaces in Imports field not being imported, and an undeclared package in an Rd object. 31 | 32 | # quanteda.textplots 0.90 33 | 34 | New version split from quanteda 2.1.2, moving the `textplot_*()` functions to a separate package as part of a modularisation of the quanteda family of packages. 35 | -------------------------------------------------------------------------------- /CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, we pledge to respect all people who 4 | contribute through reporting issues, posting feature requests, updating documentation, 5 | submitting pull requests or patches, and other activities. 6 | 7 | We are committed to making participation in this project a harassment-free experience for 8 | everyone, regardless of level of experience, gender, gender identity and expression, 9 | sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, 10 | or choice of text editor. 11 | 12 | Examples of unacceptable behavior by participants include the use of sexual language or 13 | imagery, derogatory comments or personal attacks, trolling, public or private harassment, 14 | insults, or other unprofessional conduct. 15 | 16 | Project maintainers have the right and responsibility to remove, edit, or reject comments, 17 | commits, code, wiki edits, issues, and other contributions that are not aligned to this 18 | Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed 19 | from the project team. 20 | 21 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by 22 | opening an issue or contacting one or more of the project maintainers. 23 | 24 | This Code of Conduct is adapted from the Contributor Covenant 25 | (http:contributor-covenant.org), version 1.0.0, available at 26 | http://contributor-covenant.org/version/1/0/0/ 27 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | 6 | using namespace Rcpp; 7 | 8 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 9 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 10 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 11 | #endif 12 | 13 | // qatd_cpp_is_overlap 14 | bool qatd_cpp_is_overlap(SEXP x1_, SEXP y1_, SEXP w1_, SEXP h1_, SEXP boxe_); 15 | RcppExport SEXP _quanteda_textplots_qatd_cpp_is_overlap(SEXP x1_SEXP, SEXP y1_SEXP, SEXP w1_SEXP, SEXP h1_SEXP, SEXP boxe_SEXP) { 16 | BEGIN_RCPP 17 | Rcpp::RObject rcpp_result_gen; 18 | Rcpp::RNGScope rcpp_rngScope_gen; 19 | Rcpp::traits::input_parameter< SEXP >::type x1_(x1_SEXP); 20 | Rcpp::traits::input_parameter< SEXP >::type y1_(y1_SEXP); 21 | Rcpp::traits::input_parameter< SEXP >::type w1_(w1_SEXP); 22 | Rcpp::traits::input_parameter< SEXP >::type h1_(h1_SEXP); 23 | Rcpp::traits::input_parameter< SEXP >::type boxe_(boxe_SEXP); 24 | rcpp_result_gen = Rcpp::wrap(qatd_cpp_is_overlap(x1_, y1_, w1_, h1_, boxe_)); 25 | return rcpp_result_gen; 26 | END_RCPP 27 | } 28 | 29 | static const R_CallMethodDef CallEntries[] = { 30 | {"_quanteda_textplots_qatd_cpp_is_overlap", (DL_FUNC) &_quanteda_textplots_qatd_cpp_is_overlap, 5}, 31 | {NULL, NULL, 0} 32 | }; 33 | 34 | RcppExport void R_init_quanteda_textplots(DllInfo *dll) { 35 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 36 | R_useDynamicSymbols(dll, FALSE); 37 | } 38 | -------------------------------------------------------------------------------- /.github/workflows/R-CMD-check.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | 8 | name: R-CMD-check.yaml 9 | 10 | permissions: read-all 11 | 12 | jobs: 13 | R-CMD-check: 14 | runs-on: ${{ matrix.config.os }} 15 | 16 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 17 | 18 | strategy: 19 | fail-fast: false 20 | matrix: 21 | config: 22 | - {os: macos-latest, r: 'release'} 23 | - {os: windows-latest, r: 'release'} 24 | - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} 25 | - {os: ubuntu-latest, r: 'release'} 26 | - {os: ubuntu-latest, r: 'oldrel-1'} 27 | 28 | env: 29 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 30 | R_KEEP_PKG_SOURCE: yes 31 | 32 | steps: 33 | - uses: actions/checkout@v4 34 | 35 | - uses: r-lib/actions/setup-pandoc@v2 36 | 37 | - uses: r-lib/actions/setup-r@v2 38 | with: 39 | r-version: ${{ matrix.config.r }} 40 | http-user-agent: ${{ matrix.config.http-user-agent }} 41 | use-public-rspm: true 42 | 43 | - uses: r-lib/actions/setup-r-dependencies@v2 44 | with: 45 | extra-packages: any::rcmdcheck 46 | needs: check 47 | 48 | - uses: r-lib/actions/check-r-package@v2 49 | with: 50 | upload-snapshots: true 51 | build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' 52 | -------------------------------------------------------------------------------- /tests/testthat/test-textplot_keyness.R: -------------------------------------------------------------------------------- 1 | library("quanteda") 2 | 3 | pdf(file = tempfile(".pdf"), width = 10, height = 10) 4 | 5 | test_that("test textplot_keyness: show_reference works correctly ", { 6 | skip("until quanteda.textstats is updated") 7 | presdfm <- corpus_subset(data_corpus_inaugural, President %in% c("Obama", "Trump")) |> 8 | tokens(remove_punct = TRUE) |> 9 | tokens_remove(stopwords("en")) |> 10 | dfm() 11 | presdfm <- dfm_group(presdfm, groups = presdfm$President) 12 | result <- quanteda.textstats::textstat_keyness(presdfm, target = "Trump") 13 | 14 | k <- 10 15 | p1 <- textplot_keyness(result, show_reference = FALSE, n = k) 16 | p2 <- textplot_keyness(result, show_reference = TRUE, n = k) 17 | 18 | # raises error when min_count is too high 19 | expect_error(textplot_keyness(result, show_reference = FALSE, min_count = 100), 20 | "Too few words in the documents") 21 | # plot with two different fills when show_reference = TRUE 22 | expect_equal(dim(table(ggplot2::ggplot_build(p1)$data[[1]]$colour)), 1) 23 | expect_equal(dim(table(ggplot2::ggplot_build(p2)$data[[1]]$colour)), 2) 24 | 25 | # number of words plotted doubled when show_reference = TRUE 26 | expect_equal(nrow(ggplot2::ggplot_build(p1)$data[[1]]), k) 27 | expect_equal(nrow(ggplot2::ggplot_build(p2)$data[[1]]), 2 * k) 28 | 29 | # works with integer colour 30 | expect_silent(textplot_keyness(result, color = 1:2)) 31 | 32 | # test that textplot_keyness works with pallette (vector > 2 colours) 33 | expect_silent(textplot_keyness(result, show_reference = TRUE, 34 | color = RColorBrewer::brewer.pal(6, "Dark2"))) 35 | }) 36 | 37 | dev.off() 38 | -------------------------------------------------------------------------------- /man/quanteda.textplots-package.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/quanteda.textplots-package.R 3 | \docType{package} 4 | \name{quanteda.textplots-package} 5 | \alias{quanteda.textplots} 6 | \alias{quanteda.textplots-package} 7 | \title{quanteda.textplots: Plots for the Quantitative Analysis of Textual Data} 8 | \description{ 9 | Plotting functions for visualising textual data. Extends 'quanteda' and related packages with plot methods designed specifically for text data, textual statistics, and models fit to textual data. Plot types include word clouds, lexical dispersion plots, scaling plots, network visualisations, and word 'keyness' plots. 10 | } 11 | \seealso{ 12 | Useful links: 13 | \itemize{ 14 | \item Report bugs at \url{https://github.com/quanteda/quanteda.textplots/issues} 15 | } 16 | 17 | } 18 | \author{ 19 | \strong{Maintainer}: Kenneth Benoit \email{kbenoit@lse.ac.uk} (\href{https://orcid.org/0000-0002-0797-564X}{ORCID}) [copyright holder] 20 | 21 | Authors: 22 | \itemize{ 23 | \item Kohei Watanabe \email{watanabe.kohei@gmail.com} (\href{https://orcid.org/0000-0001-6519-5265}{ORCID}) 24 | \item Haiyan Wang \email{whyinsa@yahoo.com} (\href{https://orcid.org/0000-0003-4992-4311}{ORCID}) 25 | \item Adam Obeng \email{quanteda@binaryeagle.com} (\href{https://orcid.org/0000-0002-2906-4775}{ORCID}) 26 | \item Stefan Müller \email{mullers@tcd.ie} (\href{https://orcid.org/0000-0002-6315-4125}{ORCID}) 27 | \item Akitaka Matsuo \email{a.matsuo@lse.ac.uk} (\href{https://orcid.org/0000-0002-3323-6330}{ORCID}) 28 | } 29 | 30 | Other contributors: 31 | \itemize{ 32 | \item Ian Fellows \email{ian@fellstat.com} (authored wordcloud C source code (modified)) [copyright holder] 33 | \item European Research Council (ERC-2011-StG 283794-QUANTESS) [funder] 34 | } 35 | 36 | } 37 | \keyword{internal} 38 | -------------------------------------------------------------------------------- /.github/workflows/test-coverage.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | 8 | name: test-coverage.yaml 9 | 10 | permissions: read-all 11 | 12 | jobs: 13 | test-coverage: 14 | runs-on: ubuntu-latest 15 | env: 16 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 17 | 18 | steps: 19 | - uses: actions/checkout@v4 20 | 21 | - uses: r-lib/actions/setup-r@v2 22 | with: 23 | use-public-rspm: true 24 | 25 | - uses: r-lib/actions/setup-r-dependencies@v2 26 | with: 27 | extra-packages: any::covr, any::xml2 28 | needs: coverage 29 | 30 | - name: Test coverage 31 | run: | 32 | cov <- covr::package_coverage( 33 | quiet = FALSE, 34 | clean = FALSE, 35 | install_path = file.path(normalizePath(Sys.getenv("RUNNER_TEMP"), winslash = "/"), "package") 36 | ) 37 | print(cov) 38 | covr::to_cobertura(cov) 39 | shell: Rscript {0} 40 | 41 | - uses: codecov/codecov-action@v5 42 | with: 43 | # Fail if error if not on PR, or if on PR and token is given 44 | fail_ci_if_error: ${{ github.event_name != 'pull_request' || secrets.CODECOV_TOKEN }} 45 | files: ./cobertura.xml 46 | plugins: noop 47 | disable_search: true 48 | token: ${{ secrets.CODECOV_TOKEN }} 49 | 50 | - name: Show testthat output 51 | if: always() 52 | run: | 53 | ## -------------------------------------------------------------------- 54 | find '${{ runner.temp }}/package' -name 'testthat.Rout*' -exec cat '{}' \; || true 55 | shell: bash 56 | 57 | - name: Upload test results 58 | if: failure() 59 | uses: actions/upload-artifact@v4 60 | with: 61 | name: coverage-test-failures 62 | path: ${{ runner.temp }}/package 63 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: quanteda.textplots 2 | Title: Plots for the Quantitative Analysis of Textual Data 3 | Version: 0.96.1 4 | Authors@R: 5 | c( 6 | person("Kenneth", "Benoit", email = "kbenoit@lse.ac.uk", role = c("cre", "aut", "cph"), comment = c(ORCID = "0000-0002-0797-564X")), 7 | person("Kohei", "Watanabe", email = "watanabe.kohei@gmail.com", role = c("aut"), comment = c(ORCID = "0000-0001-6519-5265")), 8 | person("Haiyan", "Wang", email = "whyinsa@yahoo.com", role = "aut", comment = c(ORCID = "0000-0003-4992-4311")), 9 | person("Adam", "Obeng", email = "quanteda@binaryeagle.com", role = "aut", comment = c(ORCID = "0000-0002-2906-4775")), 10 | person("Stefan", "Müller", email = "mullers@tcd.ie", role = "aut", comment = c(ORCID = "0000-0002-6315-4125")), 11 | person("Akitaka", "Matsuo", email = "a.matsuo@lse.ac.uk", role = "aut", comment = c(ORCID = "0000-0002-3323-6330")), 12 | person("Ian", "Fellows", email = "ian@fellstat.com", role = "cph", comment = "authored wordcloud C source code (modified)"), 13 | person("European Research Council", role = "fnd", comment = "ERC-2011-StG 283794-QUANTESS") 14 | ) 15 | Description: Plotting functions for visualising textual data. Extends 'quanteda' and 16 | related packages with plot methods designed specifically for text data, textual statistics, 17 | and models fit to textual data. Plot types include word clouds, lexical dispersion plots, 18 | scaling plots, network visualisations, and word 'keyness' plots. 19 | License: GPL-3 20 | Depends: 21 | R (>= 4.1.0) 22 | Imports: 23 | quanteda, 24 | ggplot2, 25 | ggrepel, 26 | grid, 27 | sna, 28 | igraph, 29 | Matrix, 30 | methods, 31 | network, 32 | RColorBrewer, 33 | Rcpp (>= 0.12.12), 34 | stringi 35 | LinkingTo: Rcpp 36 | Suggests: 37 | knitr, 38 | quanteda.textmodels, 39 | quanteda.textstats, 40 | rmarkdown, 41 | spelling, 42 | testthat, 43 | wordcloud 44 | Encoding: UTF-8 45 | BugReports: https://github.com/quanteda/quanteda.textplots/issues 46 | Language: en-GB 47 | Roxygen: list(markdown = TRUE) 48 | RoxygenNote: 7.3.3 49 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | S3method(as.igraph,fcm) 4 | S3method(as.network,default) 5 | S3method(as.network,fcm) 6 | S3method(textplot_keyness,default) 7 | S3method(textplot_keyness,keyness) 8 | S3method(textplot_network,dfm) 9 | S3method(textplot_network,fcm) 10 | S3method(textplot_scale1d,default) 11 | S3method(textplot_scale1d,predict.textmodel_wordscores) 12 | S3method(textplot_scale1d,textmodel_ca) 13 | S3method(textplot_scale1d,textmodel_wordfish) 14 | S3method(textplot_scale1d,textmodel_wordscores) 15 | S3method(textplot_wordcloud,default) 16 | S3method(textplot_wordcloud,dfm) 17 | S3method(textplot_wordcloud,keyness) 18 | S3method(textplot_xray,default) 19 | S3method(textplot_xray,kwic) 20 | export(as.igraph) 21 | export(as.network) 22 | export(textplot_keyness) 23 | export(textplot_network) 24 | export(textplot_scale1d) 25 | export(textplot_wordcloud) 26 | export(textplot_xray) 27 | import(ggplot2) 28 | importFrom(Rcpp,evalCpp) 29 | importFrom(ggplot2,aes) 30 | importFrom(ggplot2,coord_flip) 31 | importFrom(ggplot2,element_blank) 32 | importFrom(ggplot2,element_line) 33 | importFrom(ggplot2,facet_grid) 34 | importFrom(ggplot2,geom_point) 35 | importFrom(ggplot2,geom_pointrange) 36 | importFrom(ggplot2,geom_text) 37 | importFrom(ggplot2,ggplot) 38 | importFrom(ggplot2,theme) 39 | importFrom(ggplot2,theme_bw) 40 | importFrom(ggplot2,xlab) 41 | importFrom(ggplot2,ylab) 42 | importFrom(graphics,text) 43 | importFrom(methods,.hasSlot) 44 | importFrom(quanteda,as.dfm) 45 | importFrom(quanteda,dfm_trim) 46 | importFrom(quanteda,dfm_weight) 47 | importFrom(quanteda,fcm) 48 | importFrom(quanteda,featnames) 49 | importFrom(quanteda,is.kwic) 50 | importFrom(quanteda,meta) 51 | importFrom(quanteda,ndoc) 52 | importFrom(quanteda,nfeat) 53 | importFrom(quanteda,ntoken) 54 | importFrom(stats,aggregate) 55 | importFrom(stats,coef) 56 | importFrom(stats,quantile) 57 | importFrom(stats,reorder) 58 | importFrom(utils,head) 59 | importFrom(utils,tail) 60 | importMethodsFrom(Matrix,colSums) 61 | importMethodsFrom(Matrix,rowSums) 62 | importMethodsFrom(Matrix,t) 63 | importMethodsFrom(quanteda,t) 64 | useDynLib("quanteda.textplots", .registration = TRUE) 65 | -------------------------------------------------------------------------------- /man/textplot_xray.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_xray.R 3 | \name{textplot_xray} 4 | \alias{textplot_xray} 5 | \title{Plot the dispersion of key word(s)} 6 | \usage{ 7 | textplot_xray(..., scale = c("absolute", "relative"), sort = FALSE) 8 | } 9 | \arguments{ 10 | \item{...}{any number of \link[quanteda:kwic]{kwic} class objects} 11 | 12 | \item{scale}{\code{"relative"} or \code{"absolute"}: whether to scale the token index 13 | axis by absolute position of the token in the document or by relative 14 | position. Defaults are \code{"absolute"} for single document and \code{"relative"} 15 | for multiple documents.} 16 | 17 | \item{sort}{whether to sort the rows of a multiple document plot by document 18 | name} 19 | } 20 | \value{ 21 | a \pkg{ggplot2} object 22 | } 23 | \description{ 24 | Plots a dispersion or "x-ray" plot of selected word pattern(s) across one or 25 | more texts. The format of the plot depends on the number of 26 | \link[quanteda:kwic]{kwic} class objects passed: if there is only one document, 27 | keywords are plotted one below the other. If there are multiple documents the 28 | documents are plotted one below the other, with keywords shown side-by-side. 29 | Given that this returns a \pkg{ggplot2} object, you can modify the plot by 30 | adding \pkg{ggplot2} layers (see example). 31 | } 32 | \section{Known Issues}{ 33 | 34 | These are known issues on which we are working to solve in future versions: 35 | \itemize{ 36 | \item \code{textplot_xray()} will not display the patterns correctly when 37 | these are multi-token sequences. 38 | \item For dictionaries with keys that have overlapping value matches to tokens in 39 | the text, only the first match will be used in the plot. The way around this 40 | is to produce one kwic per dictionary key, and send them as a list to 41 | \code{textplot_xray}. 42 | } 43 | } 44 | 45 | \examples{ 46 | library("quanteda") 47 | toks <- data_corpus_inaugural |> 48 | corpus_subset(Year > 1970) |> 49 | tokens() 50 | # compare multiple documents 51 | textplot_xray(kwic(toks, pattern = "american")) 52 | textplot_xray(kwic(toks, pattern = "american"), scale = "absolute") 53 | 54 | # compare multiple terms across multiple documents 55 | textplot_xray(kwic(toks, pattern = "america*"), 56 | kwic(toks, pattern = "people")) 57 | 58 | \dontrun{ 59 | # how to modify the ggplot with different options 60 | library("ggplot2") 61 | tplot <- textplot_xray(kwic(toks, pattern = "american"), 62 | kwic(toks, pattern = "people")) 63 | tplot + aes(color = keyword) + scale_color_manual(values = c('red', 'blue')) 64 | 65 | # adjust the names of the document names 66 | docnames(toks) <- apply(docvars(toks, c("Year", "President")), 1, paste, collapse = ", ") 67 | textplot_xray(kwic(toks, pattern = "america*"), 68 | kwic(toks, pattern = "people")) 69 | } 70 | } 71 | \keyword{textplot} 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # quanteda.textplots: plots and visualisation for quanteda 3 | 4 | 5 | 6 | [![CRAN 7 | Version](https://www.r-pkg.org/badges/version/quanteda.textplots)](https://CRAN.R-project.org/package=quanteda.textplots) 8 | [![](https://img.shields.io/badge/devel%20version-0.96-royalblue.svg)](https://github.com/quanteda/quanteda.textplots) 9 | [![Downloads](https://cranlogs.r-pkg.org/badges/quanteda.textplots)](https://CRAN.R-project.org/package=quanteda.textplots) 10 | [![Total 11 | Downloads](https://cranlogs.r-pkg.org/badges/grand-total/quanteda.textplots?color=orange)](https://CRAN.R-project.org/package=quanteda.textplots) 12 | [![R-CMD-check](https://github.com/quanteda/quanteda.textplots/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/quanteda/quanteda.textplots/actions/workflows/R-CMD-check.yaml) 13 | [![Codecov test 14 | coverage](https://codecov.io/gh/quanteda/quanteda.textplots/graph/badge.svg)](https://app.codecov.io/gh/quanteda/quanteda.textplots) 15 | [![DOI](http://joss.theoj.org/papers/10.21105/joss.00774/status.svg)](https://doi.org/10.21105/joss.00774) 16 | 17 | 18 | ## About 19 | 20 | Contains the `textplot_*()` functions formerly in **quanteda**. For more 21 | details, see . 22 | 23 | ## How to Install 24 | 25 | The normal way from CRAN, using your R GUI or 26 | 27 | ``` r 28 | install.packages("quanteda.textplots") 29 | ``` 30 | 31 | Or for the latest development version: 32 | 33 | ``` r 34 | remotes::install_github("quanteda/quanteda.textplots") 35 | ``` 36 | 37 | ## How to cite 38 | 39 | Benoit, Kenneth, Kohei Watanabe, Haiyan Wang, Paul Nulty, Adam Obeng, 40 | Stefan Müller, and Akitaka Matsuo. (2018) “[quanteda: An R package for 41 | the quantitative analysis of textual 42 | data](https://www.theoj.org/joss-papers/joss.00774/10.21105.joss.00774.pdf)”. 43 | *Journal of Open Source Software*. 3(30), 774. 44 | . 45 | 46 | For a BibTeX entry, use the output from 47 | `citation(package = "quanteda.textplots")`. 48 | 49 | ## Leaving Feedback 50 | 51 | If you like **quanteda**, please consider leaving [feedback or a 52 | testimonial here](https://github.com/quanteda/quanteda/issues/461). 53 | 54 | ## Contributing 55 | 56 | Contributions in the form of feedback, comments, code, and bug reports 57 | are most welcome. How to contribute: 58 | 59 | - Fork the source code, modify, and issue a [pull 60 | request](https://help.github.com/articles/creating-a-pull-request-from-a-fork/) 61 | through the [project GitHub 62 | page](https://github.com/quanteda/quanteda.textplots). See our 63 | [Contributor Code of 64 | Conduct](https://github.com/quanteda/quanteda/blob/master/CONDUCT.md) 65 | and the all-important **quanteda** [Style 66 | Guide](https://github.com/quanteda/quanteda/wiki/Style-guide). 67 | - Issues, bug reports, and wish lists: [File a GitHub 68 | issue](https://github.com/quanteda/quanteda.textplots/issues). 69 | - Usage questions: Submit a question on the [**quanteda** channel on 70 | StackOverflow](https://stackoverflow.com/questions/tagged/quanteda). 71 | -------------------------------------------------------------------------------- /man/wordcloud_comparison.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_wordcloud.R 3 | \name{wordcloud_comparison} 4 | \alias{wordcloud_comparison} 5 | \title{Internal function for textplot_wordcloud} 6 | \usage{ 7 | wordcloud_comparison( 8 | x, 9 | min_size, 10 | max_size, 11 | min_count, 12 | max_words, 13 | color, 14 | font, 15 | adjust, 16 | rotation, 17 | random_order, 18 | random_color, 19 | ordered_color, 20 | labelcolor, 21 | labelsize, 22 | labeloffset, 23 | fixed_aspect, 24 | colors, 25 | scale, 26 | min.freq, 27 | max.words, 28 | random.order, 29 | rot.per, 30 | use.r.layout, 31 | title.size, 32 | ... 33 | ) 34 | } 35 | \arguments{ 36 | \item{x}{a \link[quanteda:dfm]{dfm} or \link[quanteda.textstats:textstat_keyness]{quanteda.textstats::textstat_keyness} 37 | object} 38 | 39 | \item{min_size}{size of the smallest word} 40 | 41 | \item{max_size}{size of the largest word} 42 | 43 | \item{min_count}{words with frequency below min_count will not be plotted} 44 | 45 | \item{max_words}{maximum number of words to be plotted. The least frequent 46 | terms dropped. The maximum frequency will be split evenly across 47 | categories when \code{comparison = TRUE}.} 48 | 49 | \item{color}{colour of words from least to most frequent} 50 | 51 | \item{font}{font-family of words and labels. Use default font if \code{NULL}.} 52 | 53 | \item{adjust}{adjust sizes of words by a constant. Useful for non-English 54 | words for which R fails to obtain correct sizes.} 55 | 56 | \item{rotation}{proportion of words with 90 degree rotation} 57 | 58 | \item{random_order}{plot words in random order. If \code{FALSE}, they will be 59 | plotted in decreasing frequency.} 60 | 61 | \item{random_color}{choose colours randomly from the colours. If \code{FALSE}, 62 | the colour is chosen based on the frequency} 63 | 64 | \item{ordered_color}{if \code{TRUE}, then colours are assigned to words in 65 | order.} 66 | 67 | \item{labelcolor}{colour of group labels. Only used when \code{comparison = TRUE}.} 68 | 69 | \item{labelsize}{size of group labels. Only used when \code{comparison = TRUE}.} 70 | 71 | \item{labeloffset}{position of group labels. Only used when 72 | \code{comparison = TRUE}.} 73 | 74 | \item{fixed_aspect}{logical; if \code{TRUE}, the aspect ratio is fixed. Variable 75 | aspect ratio only supported if rotation = 0.} 76 | 77 | \item{scale}{deprecated argument} 78 | 79 | \item{min.freq}{deprecated argument} 80 | 81 | \item{max.words}{deprecated argument} 82 | 83 | \item{random.order}{deprecated argument} 84 | 85 | \item{rot.per}{deprecated argument} 86 | 87 | \item{use.r.layout}{deprecated argument} 88 | 89 | \item{title.size}{deprecated argument} 90 | 91 | \item{...}{additional parameters. Only used to make it compatible with 92 | \pkg{wordcloud}} 93 | } 94 | \description{ 95 | This function implements wordcloud that compares documents. Code is adopted 96 | from \code{\link[wordcloud:comparison.cloud]{wordcloud::comparison.cloud()}}. 97 | } 98 | \author{ 99 | Kohei Watanabe, build on code from Ian Fellows's \pkg{wordcloud} package. 100 | } 101 | \keyword{internal} 102 | \keyword{textplot_internal} 103 | -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | output: github_document 3 | --- 4 | 5 | ```{r, echo = FALSE} 6 | knitr::opts_chunk$set( 7 | collapse = TRUE, 8 | comment = "##", 9 | fig.path = "man/images/" 10 | ) 11 | ``` 12 | ```{r echo=FALSE, results="hide", message=FALSE} 13 | library("badger") 14 | ``` 15 | 16 | # quanteda.textplots: plots and visualisation for quanteda 17 | 18 | 19 | [![CRAN Version](https://www.r-pkg.org/badges/version/quanteda.textplots)](https://CRAN.R-project.org/package=quanteda.textplots) 20 | `r badge_devel("quanteda/quanteda.textplots", "royalblue")` 21 | [![Downloads](https://cranlogs.r-pkg.org/badges/quanteda.textplots)](https://CRAN.R-project.org/package=quanteda.textplots) 22 | [![Total Downloads](https://cranlogs.r-pkg.org/badges/grand-total/quanteda.textplots?color=orange)](https://CRAN.R-project.org/package=quanteda.textplots) 23 | [![R-CMD-check](https://github.com/quanteda/quanteda.textplots/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/quanteda/quanteda.textplots/actions/workflows/R-CMD-check.yaml) 24 | [![Codecov test coverage](https://codecov.io/gh/quanteda/quanteda.textplots/graph/badge.svg)](https://app.codecov.io/gh/quanteda/quanteda.textplots) 25 | [![DOI](http://joss.theoj.org/papers/10.21105/joss.00774/status.svg)](https://doi.org/10.21105/joss.00774) 26 | 27 | 28 | ## About 29 | 30 | Contains the `textplot_*()` functions formerly in **quanteda**. For more details, see https://quanteda.io. 31 | 32 | ## How to Install 33 | 34 | The normal way from CRAN, using your R GUI or 35 | ```{r eval = FALSE} 36 | install.packages("quanteda.textplots") 37 | ``` 38 | 39 | Or for the latest development version: 40 | ```{r eval = FALSE} 41 | remotes::install_github("quanteda/quanteda.textplots") 42 | ``` 43 | 44 | ## How to cite 45 | 46 | Benoit, Kenneth, Kohei Watanabe, Haiyan Wang, Paul Nulty, Adam Obeng, Stefan Müller, and Akitaka Matsuo. (2018) "[quanteda: An R package for the quantitative analysis of textual data](https://www.theoj.org/joss-papers/joss.00774/10.21105.joss.00774.pdf)". _Journal of Open Source Software_. 3(30), 774. [https://doi.org/10.21105/joss.00774](https://doi.org/10.21105/joss.00774). 47 | 48 | For a BibTeX entry, use the output from `citation(package = "quanteda.textplots")`. 49 | 50 | ## Leaving Feedback 51 | 52 | If you like **quanteda**, please consider leaving [feedback or a testimonial here](https://github.com/quanteda/quanteda/issues/461). 53 | 54 | ## Contributing 55 | 56 | Contributions in the form of feedback, comments, code, and bug reports are most welcome. How to contribute: 57 | 58 | * Fork the source code, modify, and issue a [pull request](https://help.github.com/articles/creating-a-pull-request-from-a-fork/) through the [project GitHub page](https://github.com/quanteda/quanteda.textplots). See our [Contributor Code of Conduct](https://github.com/quanteda/quanteda/blob/master/CONDUCT.md) and the all-important **quanteda** [Style Guide](https://github.com/quanteda/quanteda/wiki/Style-guide). 59 | * Issues, bug reports, and wish lists: [File a GitHub issue](https://github.com/quanteda/quanteda.textplots/issues). 60 | * Usage questions: Submit a question on the [**quanteda** channel on StackOverflow](https://stackoverflow.com/questions/tagged/quanteda). 61 | 62 | 63 | -------------------------------------------------------------------------------- /tests/testthat/test-textplot_scale1d.R: -------------------------------------------------------------------------------- 1 | pdf(file = tempfile(".pdf"), width = 10, height = 10) 2 | 3 | test_that("test textplot_scale1d wordfish in the most basic way", { 4 | skip_if_not_installed("quanteda.textmodels") 5 | require("quanteda.textmodels") 6 | wf <- textmodel_wordfish(dfm(tokens(data_corpus_irishbudget2010)), dir = c(6, 5)) 7 | expect_false(identical(textplot_scale1d(wf, sort = TRUE), 8 | textplot_scale1d(wf, sort = FALSE))) 9 | expect_silent(textplot_scale1d(wf, sort = TRUE, 10 | groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) 11 | expect_silent(textplot_scale1d(wf, sort = FALSE, 12 | groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) 13 | 14 | expect_silent( 15 | textplot_scale1d(wf, doclabels = apply(quanteda::docvars(data_corpus_irishbudget2010, 16 | c("name", "party")), 17 | 1, paste, collapse = " ")) 18 | ) 19 | 20 | p1 <- textplot_scale1d(wf, margin = "features", sort = TRUE) 21 | p2 <- textplot_scale1d(wf, margin = "features", sort = FALSE) 22 | p1$plot_env <- NULL 23 | p2$plot_env <- NULL 24 | expect_equal(p1, p2, check.environment = FALSE) 25 | }) 26 | 27 | test_that("test textplot_scale1d wordscores in the most basic way", { 28 | skip_if_not_installed("quanteda.textmodels") 29 | mt <- dfm(tokens(data_corpus_irishbudget2010)) 30 | ws <- quanteda.textmodels::textmodel_wordscores(mt, c(rep(NA, 4), -1, 1, rep(NA, 8))) 31 | pr <- suppressWarnings(predict(ws, mt, force = TRUE)) 32 | 33 | ca <- quanteda.textmodels::textmodel_ca(mt) 34 | 35 | expect_false(identical(textplot_scale1d(pr, sort = TRUE), 36 | textplot_scale1d(pr, sort = FALSE))) 37 | expect_silent(textplot_scale1d(pr, sort = TRUE, 38 | groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) 39 | expect_silent(textplot_scale1d(pr, sort = FALSE, 40 | groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) 41 | 42 | expect_silent(textplot_scale1d(pr, doclabels = apply(quanteda::docvars(data_corpus_irishbudget2010, 43 | c("name", "party")), 44 | 1, paste, collapse = " "))) 45 | 46 | expect_silent(textplot_scale1d(ca)) 47 | expect_silent(textplot_scale1d(ca, groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) 48 | 49 | p1 <- textplot_scale1d(ws, margin = "features", sort = TRUE) 50 | p2 <- textplot_scale1d(ws, margin = "features", sort = FALSE) 51 | p1$plot_env <- NULL 52 | p2$plot_env <- NULL 53 | expect_equal(p1, p2, check.environment = FALSE) 54 | 55 | expect_error( 56 | textplot_scale1d(ws, margin = "documents"), 57 | "This margin can only be run on a predicted wordscores object" 58 | ) 59 | expect_error( 60 | suppressWarnings(textplot_scale1d(predict(ws), margin = "features")), 61 | "This margin can only be run on a fitted wordscores object" 62 | ) 63 | }) 64 | 65 | dev.off() 66 | -------------------------------------------------------------------------------- /man/wordcloud.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_wordcloud.R 3 | \name{wordcloud} 4 | \alias{wordcloud} 5 | \title{Internal function for textplot_wordcloud} 6 | \usage{ 7 | wordcloud( 8 | x, 9 | min_size, 10 | max_size, 11 | min_count, 12 | max_words, 13 | color, 14 | font, 15 | adjust, 16 | rotation, 17 | random_order, 18 | random_color, 19 | ordered_color, 20 | labelcolor, 21 | labelsize, 22 | labeloffset, 23 | fixed_aspect, 24 | colors, 25 | scale, 26 | min.freq, 27 | max.words, 28 | random.order, 29 | random.color, 30 | rot.per, 31 | ordered.colors, 32 | use.r.layout, 33 | fixed.asp, 34 | ... 35 | ) 36 | } 37 | \arguments{ 38 | \item{x}{a \link[quanteda:dfm]{dfm} or \link[quanteda.textstats:textstat_keyness]{quanteda.textstats::textstat_keyness} 39 | object} 40 | 41 | \item{min_size}{size of the smallest word} 42 | 43 | \item{max_size}{size of the largest word} 44 | 45 | \item{min_count}{words with frequency below min_count will not be plotted} 46 | 47 | \item{max_words}{maximum number of words to be plotted. The least frequent 48 | terms dropped. The maximum frequency will be split evenly across 49 | categories when \code{comparison = TRUE}.} 50 | 51 | \item{color}{colour of words from least to most frequent} 52 | 53 | \item{font}{font-family of words and labels. Use default font if \code{NULL}.} 54 | 55 | \item{adjust}{adjust sizes of words by a constant. Useful for non-English 56 | words for which R fails to obtain correct sizes.} 57 | 58 | \item{rotation}{proportion of words with 90 degree rotation} 59 | 60 | \item{random_order}{plot words in random order. If \code{FALSE}, they will be 61 | plotted in decreasing frequency.} 62 | 63 | \item{random_color}{choose colours randomly from the colours. If \code{FALSE}, 64 | the colour is chosen based on the frequency} 65 | 66 | \item{ordered_color}{if \code{TRUE}, then colours are assigned to words in 67 | order.} 68 | 69 | \item{labelcolor}{colour of group labels. Only used when \code{comparison = TRUE}.} 70 | 71 | \item{labelsize}{size of group labels. Only used when \code{comparison = TRUE}.} 72 | 73 | \item{labeloffset}{position of group labels. Only used when 74 | \code{comparison = TRUE}.} 75 | 76 | \item{fixed_aspect}{logical; if \code{TRUE}, the aspect ratio is fixed. Variable 77 | aspect ratio only supported if rotation = 0.} 78 | 79 | \item{scale}{deprecated argument} 80 | 81 | \item{min.freq}{deprecated argument} 82 | 83 | \item{max.words}{deprecated argument} 84 | 85 | \item{random.order}{deprecated argument} 86 | 87 | \item{random.color}{deprecated argument} 88 | 89 | \item{rot.per}{deprecated argument} 90 | 91 | \item{ordered.colors}{deprecated argument} 92 | 93 | \item{use.r.layout}{deprecated argument} 94 | 95 | \item{fixed.asp}{deprecated argument} 96 | 97 | \item{...}{additional parameters. Only used to make it compatible with 98 | \pkg{wordcloud}} 99 | } 100 | \description{ 101 | This function implements wordcloud without dependencies. Code is adopted from 102 | \code{\link[wordcloud:wordcloud]{wordcloud::wordcloud()}}. 103 | } 104 | \author{ 105 | Kohei Watanabe, building on code from Ian Fellows's \pkg{wordcloud} package. 106 | } 107 | \keyword{internal} 108 | -------------------------------------------------------------------------------- /man/textplot_keyness.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_keyness.R 3 | \name{textplot_keyness} 4 | \alias{textplot_keyness} 5 | \title{Plot word keyness} 6 | \usage{ 7 | textplot_keyness( 8 | x, 9 | show_reference = TRUE, 10 | show_legend = TRUE, 11 | n = 20L, 12 | min_count = 2L, 13 | margin = 0.05, 14 | color = c("darkblue", "gray"), 15 | labelcolor = "gray30", 16 | labelsize = 4, 17 | font = NULL 18 | ) 19 | } 20 | \arguments{ 21 | \item{x}{a return object from \code{\link[quanteda.textstats:textstat_keyness]{quanteda.textstats::textstat_keyness()}}} 22 | 23 | \item{show_reference}{logical; if \code{TRUE}, show key reference features in 24 | addition to key target features} 25 | 26 | \item{show_legend}{logical; if \code{TRUE}, show legend} 27 | 28 | \item{n}{integer; number of features to plot} 29 | 30 | \item{min_count}{numeric; minimum total count of feature across the target 31 | and reference categories, for a feature to be included in the plot} 32 | 33 | \item{margin}{numeric; size of margin where feature labels are shown} 34 | 35 | \item{color}{character or integer; colours of bars for target and reference 36 | documents. \code{color} must have two elements when \code{show_reference = TRUE}. 37 | See \link[ggplot2:aes_colour_fill_alpha]{ggplot2::color}.} 38 | 39 | \item{labelcolor}{character; color of feature labels.} 40 | 41 | \item{labelsize}{numeric; size of feature labels and bars. See 42 | \link[ggplot2:aes_linetype_size_shape]{ggplot2::size}.} 43 | 44 | \item{font}{character; font-family of texts. Use default font if \code{NULL}.} 45 | } 46 | \value{ 47 | a \pkg{ggplot2} object 48 | } 49 | \description{ 50 | Plot the results of a "keyword" of features comparing their differential 51 | associations with a target and a reference group, after calculating keyness 52 | using \code{\link[quanteda.textstats:textstat_keyness]{quanteda.textstats::textstat_keyness()}}. 53 | } 54 | \examples{ 55 | \dontrun{ 56 | library("quanteda") 57 | # compare Trump speeches to other Presidents by chi^2 58 | dfmat1 <- data_corpus_inaugural |> 59 | corpus_subset(Year > 1980) |> 60 | tokens(remove_punct = TRUE) |> 61 | tokens_remove(stopwords("en")) |> 62 | dfm() 63 | dfmat1 <- dfm_group(dfmat1, groups = dfmat1$President) 64 | tstat1 <- quanteda.textstats::textstat_keyness(dfmat1, target = "Trump") 65 | textplot_keyness(tstat1, margin = 0.2, n = 10) 66 | tstat1 <- quanteda.textstats::textstat_keyness(dfmat1, target = "Trump") 67 | textplot_keyness(tstat1, margin = 0.2, n = 10) 68 | 69 | # compare contemporary Democrats v. Republicans 70 | corp <- data_corpus_inaugural |> 71 | corpus_subset(Year > 1960) 72 | corp$party <- ifelse(docvars(corp, "President") \%in\% c("Nixon", "Reagan", "Bush", "Trump"), 73 | "Republican", "Democrat") 74 | dfmat2 <- corp |> 75 | tokens(remove_punct = TRUE) |> 76 | tokens_remove(stopwords("en")) |> 77 | dfm() 78 | tstat2 <- quanteda.textstats::textstat_keyness(dfm_group(dfmat2, groups = dfmat2$party), 79 | target = "Democrat", measure = "lr") 80 | textplot_keyness(tstat2, color = c("blue", "red"), n = 10) 81 | } 82 | } 83 | \seealso{ 84 | \code{\link[quanteda.textstats:textstat_keyness]{quanteda.textstats::textstat_keyness()}} 85 | } 86 | \author{ 87 | Haiyan Wang and Kohei Watanabe 88 | } 89 | \keyword{textplot} 90 | -------------------------------------------------------------------------------- /tests/testthat/test-textplot_wordcloud.R: -------------------------------------------------------------------------------- 1 | pdf(file = tempfile(".pdf"), width = 10, height = 10) 2 | 3 | test_that("test textplot_wordcloud works for dfm objects", { 4 | mt <- dfm(tokens(data_corpus_inaugural[1:5])) 5 | mt <- dfm_trim(mt, min_termfreq = 10) 6 | expect_silent(textplot_wordcloud(mt)) 7 | }) 8 | 9 | test_that("test textplot_wordcloud works for keyness objects", { 10 | skip("until quanteda.textstats is updated") 11 | tstat <- head(data_corpus_inaugural, 2) |> 12 | tokens() |> 13 | tokens_remove(stopwords("en")) |> 14 | dfm() |> 15 | quanteda.textstats::textstat_keyness(target = 1) 16 | expect_silent(textplot_wordcloud(tstat, max_words = 50)) 17 | expect_silent(textplot_wordcloud(tstat, comparison = FALSE, max_words = 50)) 18 | }) 19 | 20 | test_that("test textplot_wordcloud comparison works", { 21 | skip_on_travis() 22 | skip_on_cran() 23 | skip_on_os("linux") 24 | testcorp <- corpus_reshape(corpus(data_char_sampletext)) 25 | set.seed(1) 26 | docvars(testcorp, "label") <- sample(c("A", "B"), size = ndoc(testcorp), replace = TRUE) 27 | docnames(testcorp) <- paste0("text", 1:ndoc(testcorp)) 28 | testdfm <- dfm(tokens(testcorp)) |> 29 | dfm_remove(stopwords("en")) 30 | testdfm_grouped <- dfm_group(testdfm, groups = testdfm$label) 31 | 32 | jpeg(filename = tempfile(".jpg"), width = 5000, height = 5000) 33 | expect_silent( 34 | textplot_wordcloud(testdfm_grouped, comparison = TRUE) 35 | ) 36 | expect_silent( 37 | textplot_wordcloud(testdfm_grouped, random_order = FALSE) 38 | ) 39 | expect_silent( 40 | textplot_wordcloud(testdfm_grouped, ordered_color = FALSE) 41 | ) 42 | expect_error( 43 | textplot_wordcloud(dfm(tokens(data_corpus_inaugural[1:9])), comparison = TRUE), 44 | "Too many documents to plot comparison, use 8 or fewer documents" 45 | ) 46 | 47 | dfmsmall <- dfm(tokens(data_corpus_inaugural[1:9], remove_punct = TRUE)) 48 | dfmsmall <- dfm_group(dfmsmall, groups = dfmsmall$President) |> 49 | dfm_remove(stopwords("en")) |> 50 | dfm_trim(min_termfreq = 20) 51 | expect_silent(textplot_wordcloud(dfmsmall, comparison = TRUE)) 52 | expect_silent(textplot_wordcloud(dfmsmall, color = 1:5)) 53 | expect_warning( 54 | textplot_wordcloud(dfmsmall, scale = 1:4), 55 | "scale is deprecated" 56 | ) 57 | expect_warning( 58 | textplot_wordcloud(dfmsmall, random.order = TRUE), 59 | "random.order is deprecated; use random_order instead" 60 | ) 61 | expect_warning( 62 | textplot_wordcloud(dfmsmall, max.words = 10), 63 | "max.words is deprecated; use max_words instead" 64 | ) 65 | 66 | dev.off() 67 | expect_error( 68 | textplot_wordcloud(testdfm, comparison = TRUE), 69 | "Too many documents to plot comparison, use 8 or fewer documents\\." 70 | ) 71 | }) 72 | 73 | test_that("test textplot_wordcloud raise deprecation message", { 74 | jpeg(filename = tempfile(".jpg"), width = 5000, height = 5000) 75 | mt <- dfm(tokens(data_corpus_inaugural[1:5])) 76 | mt <- dfm_trim(mt, min_termfreq = 10) 77 | expect_warning(textplot_wordcloud(mt, min.freq = 10), "min.freq is deprecated") 78 | expect_warning(textplot_wordcloud(mt, use.r.layout = 10), "use.r.layout is no longer use") 79 | dev.off() 80 | }) 81 | 82 | test_that("plotting empty dfms after trimming is caught (#1755)", { 83 | dfmat <- dfm(tokens(c("Azymuth", "Compass", "GPS", "Zenith"))) 84 | expect_error( 85 | textplot_wordcloud(dfmat, min_count = 2), 86 | "No features left after trimming with min_count = 2" 87 | ) 88 | }) 89 | 90 | dev.off() 91 | -------------------------------------------------------------------------------- /man/textplot_network.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_network.R 3 | \name{textplot_network} 4 | \alias{textplot_network} 5 | \alias{as.network.fcm} 6 | \alias{as.igraph.fcm} 7 | \title{Plot a network of feature co-occurrences} 8 | \usage{ 9 | textplot_network( 10 | x, 11 | min_freq = 0.5, 12 | omit_isolated = TRUE, 13 | edge_color = "#1F78B4", 14 | edge_alpha = 0.5, 15 | edge_size = 2, 16 | vertex_color = "#4D4D4D", 17 | vertex_size = 2, 18 | vertex_labelcolor = NULL, 19 | vertex_labelfont = NULL, 20 | vertex_labelsize = 5, 21 | offset = NULL, 22 | ... 23 | ) 24 | 25 | \method{as.network}{fcm}(x, min_freq = 0.5, omit_isolated = TRUE, ...) 26 | 27 | \method{as.igraph}{fcm}(x, min_freq = 0.5, omit_isolated = TRUE, ...) 28 | } 29 | \arguments{ 30 | \item{x}{a \link[quanteda:fcm]{fcm} or \link[quanteda:dfm]{dfm} object} 31 | 32 | \item{min_freq}{a frequency count threshold or proportion for co-occurrence 33 | frequencies of features to be included.} 34 | 35 | \item{omit_isolated}{if \code{TRUE}, features do not occur more frequent than 36 | \code{min_freq} will be omitted.} 37 | 38 | \item{edge_color}{colour of edges that connect vertices.} 39 | 40 | \item{edge_alpha}{opacity of edges ranging from 0 to 1.0.} 41 | 42 | \item{edge_size}{size of edges for most frequent co-occurrence The size of 43 | other edges are determined proportionally to the 99th percentile frequency 44 | instead of the maximum to reduce the impact of outliers.} 45 | 46 | \item{vertex_color}{colour of vertices.} 47 | 48 | \item{vertex_size}{size of vertices} 49 | 50 | \item{vertex_labelcolor}{colour of texts. Defaults to the same as 51 | \code{vertex_color}. If \code{NA} is given, texts are not rendered.} 52 | 53 | \item{vertex_labelfont}{font-family of texts. Use default font if 54 | \code{NULL}.} 55 | 56 | \item{vertex_labelsize}{size of vertex labels in mm. Defaults to size 5. 57 | Supports both integer values and vector values.} 58 | 59 | \item{offset}{if \code{NULL}, the distance between vertices and texts are 60 | determined automatically.} 61 | 62 | \item{...}{additional arguments passed to \link[network:network]{network} or 63 | \link[igraph:graph_from_adjacency_matrix]{graph_from_adjacency_matrix}. Not 64 | used for \code{as.igraph}.} 65 | } 66 | \description{ 67 | Plot an \link[quanteda:fcm]{fcm} object as a network, where edges show 68 | co-occurrences of features. 69 | } 70 | \details{ 71 | Currently the size of the network is limited to 1000, because of the 72 | computationally intensive nature of network formation for larger matrices. 73 | When the \link[quanteda:fcm]{fcm} is large, users should select features using 74 | \link[quanteda:dfm_select]{fcm_select()}, set the threshold using \code{min_freq}, 75 | or implement own plotting function using \code{\link[=as.network.fcm]{as.network()}}. 76 | } 77 | \examples{ 78 | set.seed(100) 79 | library("quanteda") 80 | toks <- data_char_ukimmig2010 |> 81 | tokens(remove_punct = TRUE) |> 82 | tokens_tolower() |> 83 | tokens_remove(pattern = stopwords("english"), padding = FALSE) 84 | fcmat <- fcm(toks, context = "window", tri = FALSE) 85 | feat <- colSums(fcmat) |> 86 | sort(decreasing = TRUE) |> 87 | head(30) |> 88 | names() 89 | fcm_select(fcmat, pattern = feat) |> 90 | textplot_network(min_freq = 0.5) 91 | fcm_select(fcmat, pattern = feat) |> 92 | textplot_network(min_freq = 0.8) 93 | fcm_select(fcmat, pattern = feat) |> 94 | textplot_network(min_freq = 0.8, vertex_labelcolor = rep(c('gray40', NA), 15)) 95 | fcm_select(fcmat, pattern = feat) |> 96 | textplot_network(vertex_labelsize = 10) 97 | fcm_30 <- fcm_select(fcmat, pattern = feat) 98 | textplot_network(fcm_30, 99 | vertex_labelsize = Matrix::rowSums(fcm_30) / min(Matrix::rowSums(fcm_30))) 100 | # Vector inputs to vertex_labelsize can be scaled if too small / large 101 | textplot_network(fcm_30, 102 | vertex_labelsize = 1.5 * Matrix::rowSums(fcm_30) / 103 | min(Matrix::rowSums(fcm_30))) 104 | 105 | # as.igraph 106 | if (requireNamespace("igraph", quietly = TRUE)) { 107 | txt <- c("a a a b b c", "a a c e", "a c e f g") 108 | mat <- fcm(tokens(txt)) 109 | as.igraph(mat, min_freq = 1, omit_isolated = FALSE) 110 | } 111 | } 112 | \seealso{ 113 | \link[quanteda:fcm]{fcm} 114 | 115 | \code{\link[network:network]{network::network()}} 116 | 117 | \code{\link[igraph:graph_from_adjacency_matrix]{igraph::graph_from_adjacency_matrix()}} 118 | } 119 | \author{ 120 | Kohei Watanabe and Stefan Müller 121 | } 122 | \keyword{textplot} 123 | -------------------------------------------------------------------------------- /man/textplot_scale1d.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_scale1d.R 3 | \name{textplot_scale1d} 4 | \alias{textplot_scale1d} 5 | \title{Plot a fitted scaling model} 6 | \usage{ 7 | textplot_scale1d( 8 | x, 9 | margin = c("documents", "features"), 10 | doclabels = NULL, 11 | sort = TRUE, 12 | groups = NULL, 13 | highlighted = NULL, 14 | alpha = 0.7, 15 | highlighted_color = "black" 16 | ) 17 | } 18 | \arguments{ 19 | \item{x}{the fitted or predicted scaling model object to be plotted} 20 | 21 | \item{margin}{\code{"documents"} to plot estimated document scores (the 22 | default) or \code{"features"} to plot estimated feature scores by a measure 23 | of relative frequency} 24 | 25 | \item{doclabels}{a vector of names for document; if left NULL (the default), 26 | docnames will be used} 27 | 28 | \item{sort}{if \code{TRUE} (the default), order points from low to high 29 | score. If a vector, order according to these values from low to high. Only 30 | applies when \code{margin = "documents"}.} 31 | 32 | \item{groups}{grouping variable for sampling, equal in length to the number 33 | of documents. This will be evaluated in the docvars data.frame, so that 34 | docvars may be referred to by name without quoting. This also changes 35 | previous behaviours for \code{groups}. See \code{news(Version >= "3.0", package = "quanteda")} for details.} 36 | 37 | \item{highlighted}{a vector of feature names to draw attention to in a 38 | feature plot; only applies if \code{margin = "features"}} 39 | 40 | \item{alpha}{A number between 0 and 1 (default 0.5) representing the level of 41 | alpha transparency used to overplot feature names in a feature plot; only 42 | applies if \code{margin = "features"}} 43 | 44 | \item{highlighted_color}{colour for highlighted terms in \code{highlighted}} 45 | } 46 | \value{ 47 | a \pkg{ggplot2} object 48 | } 49 | \description{ 50 | Plot the results of a fitted scaling model, from (e.g.) a predicted 51 | \link[quanteda.textmodels:textmodel_wordscores]{quanteda.textmodels::textmodel_wordscores} model or a fitted 52 | \link[quanteda.textmodels:textmodel_wordfish]{quanteda.textmodels::textmodel_wordfish} or 53 | \link[quanteda.textmodels:textmodel_ca]{quanteda.textmodels::textmodel_ca} model. Either document or feature 54 | parameters may be plotted: an ideal point-style plot (estimated document 55 | position plus confidence interval on the x-axis, document labels on the 56 | y-axis) with optional renaming and sorting, or as a plot of estimated 57 | feature-level parameters (estimated feature positions on the x-axis, and a 58 | measure of relative frequency or influence on the y-axis, with feature names 59 | replacing plotting points with some being chosen by the user to be 60 | highlighted). 61 | } 62 | \note{ 63 | The \code{groups} argument only applies when \code{margin = "documents"}. 64 | } 65 | \examples{ 66 | library("quanteda") 67 | if (require("quanteda.textmodels")) { 68 | dfmat <- dfm(tokens(data_corpus_irishbudget2010)) 69 | 70 | ## wordscores 71 | refscores <- c(rep(NA, 4), 1, -1, rep(NA, 8)) 72 | tmod1 <- textmodel_wordscores(dfmat, y = refscores, smooth = 1) 73 | # plot estimated document positions 74 | textplot_scale1d(predict(tmod1, se.fit = TRUE), 75 | groups = data_corpus_irishbudget2010$party) 76 | # plot estimated word positions 77 | textplot_scale1d(tmod1, margin = "features", 78 | highlighted = c("minister", "have", "our", "budget")) 79 | 80 | ## wordfish 81 | tmod2 <- quanteda.textmodels::textmodel_wordfish(dfmat, dir = c(6,5)) 82 | # plot estimated document positions 83 | textplot_scale1d(tmod2) 84 | textplot_scale1d(tmod2, groups = data_corpus_irishbudget2010$party) 85 | # plot estimated word positions 86 | textplot_scale1d(tmod2, margin = "features", 87 | highlighted = c("government", "global", "children", 88 | "bank", "economy", "the", "citizenship", 89 | "productivity", "deficit")) 90 | 91 | ## correspondence analysis 92 | tmod3 <- textmodel_ca(dfmat) 93 | # plot estimated document positions 94 | textplot_scale1d(tmod3, margin = "documents", 95 | groups = docvars(data_corpus_irishbudget2010, "party")) 96 | } 97 | } 98 | \seealso{ 99 | \code{\link[quanteda.textmodels:textmodel_wordfish]{quanteda.textmodels::textmodel_wordfish()}}, 100 | \code{\link[quanteda.textmodels:textmodel_wordscores]{quanteda.textmodels::textmodel_wordscores()}}, 101 | \code{\link[quanteda.textmodels:textmodel_ca]{quanteda.textmodels::textmodel_ca()}} 102 | } 103 | \author{ 104 | Kenneth Benoit, Stefan Müller, and Adam Obeng 105 | } 106 | \keyword{textplot} 107 | -------------------------------------------------------------------------------- /man/textplot_wordcloud.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/textplot_wordcloud.R 3 | \name{textplot_wordcloud} 4 | \alias{textplot_wordcloud} 5 | \title{Plot features as a wordcloud} 6 | \usage{ 7 | textplot_wordcloud( 8 | x, 9 | min_size = 0.5, 10 | max_size = 4, 11 | min_count = 3, 12 | max_words = 500, 13 | color = "darkblue", 14 | font = NULL, 15 | adjust = 0, 16 | rotation = 0.1, 17 | random_order = FALSE, 18 | random_color = FALSE, 19 | ordered_color = FALSE, 20 | labelcolor = "gray20", 21 | labelsize = 1.5, 22 | labeloffset = 0, 23 | fixed_aspect = TRUE, 24 | ..., 25 | comparison = FALSE 26 | ) 27 | } 28 | \arguments{ 29 | \item{x}{a \link[quanteda:dfm]{dfm} or \link[quanteda.textstats:textstat_keyness]{quanteda.textstats::textstat_keyness} 30 | object} 31 | 32 | \item{min_size}{size of the smallest word} 33 | 34 | \item{max_size}{size of the largest word} 35 | 36 | \item{min_count}{words with frequency below min_count will not be plotted} 37 | 38 | \item{max_words}{maximum number of words to be plotted. The least frequent 39 | terms dropped. The maximum frequency will be split evenly across 40 | categories when \code{comparison = TRUE}.} 41 | 42 | \item{color}{colour of words from least to most frequent} 43 | 44 | \item{font}{font-family of words and labels. Use default font if \code{NULL}.} 45 | 46 | \item{adjust}{adjust sizes of words by a constant. Useful for non-English 47 | words for which R fails to obtain correct sizes.} 48 | 49 | \item{rotation}{proportion of words with 90 degree rotation} 50 | 51 | \item{random_order}{plot words in random order. If \code{FALSE}, they will be 52 | plotted in decreasing frequency.} 53 | 54 | \item{random_color}{choose colours randomly from the colours. If \code{FALSE}, 55 | the colour is chosen based on the frequency} 56 | 57 | \item{ordered_color}{if \code{TRUE}, then colours are assigned to words in 58 | order.} 59 | 60 | \item{labelcolor}{colour of group labels. Only used when \code{comparison = TRUE}.} 61 | 62 | \item{labelsize}{size of group labels. Only used when \code{comparison = TRUE}.} 63 | 64 | \item{labeloffset}{position of group labels. Only used when 65 | \code{comparison = TRUE}.} 66 | 67 | \item{fixed_aspect}{logical; if \code{TRUE}, the aspect ratio is fixed. Variable 68 | aspect ratio only supported if rotation = 0.} 69 | 70 | \item{...}{additional parameters. Only used to make it compatible with 71 | \pkg{wordcloud}} 72 | 73 | \item{comparison}{logical; if \code{TRUE}, plot a wordcloud that compares 74 | documents in the same way as \code{\link[wordcloud:comparison.cloud]{wordcloud::comparison.cloud()}}. If \code{x} is a 75 | \link[quanteda.textstats:textstat_keyness]{quanteda.textstats::textstat_keyness} object, then only the target 76 | category's key terms are plotted when \code{comparison = FALSE}, otherwise the 77 | top \code{max_words / 2} terms are plotted from the target and reference 78 | categories.} 79 | } 80 | \description{ 81 | Plot a \link[quanteda:dfm]{dfm} or \link[quanteda.textstats:textstat_keyness]{quanteda.textstats::textstat_keyness} object 82 | as a wordcloud, where the feature labels are plotted with their sizes 83 | proportional to their numerical values in the dfm. When \code{comparison = TRUE}, 84 | it plots comparison word clouds by document (or by target and reference 85 | categories in the case of a keyness object). 86 | } 87 | \details{ 88 | The default is to plot the word cloud of all features, summed across 89 | documents. To produce word cloud plots for specific document or set of 90 | documents, you need to slice out the document(s) from the dfm object. 91 | 92 | Comparison wordcloud plots may be plotted by setting \code{comparison = TRUE}, 93 | which plots a separate grouping for \emph{each document} in the dfm. This means 94 | that you will need to slice out just a few documents from the dfm, or to 95 | create a dfm where the "documents" represent a subset or a grouping of 96 | documents by some document variable. 97 | } 98 | \examples{ 99 | # plot the features (without stopwords) from Obama's inaugural addresses 100 | set.seed(10) 101 | library("quanteda") 102 | dfmat1 <- data_corpus_inaugural |> 103 | corpus_subset(President == "Obama") |> 104 | tokens(remove_punct = TRUE) |> 105 | tokens_remove(stopwords("en")) |> 106 | dfm() |> 107 | dfm_trim(min_termfreq = 3) 108 | 109 | # basic wordcloud 110 | textplot_wordcloud(dfmat1) 111 | 112 | # plot in colours with some additional options 113 | textplot_wordcloud(dfmat1, rotation = 0.25, 114 | color = rev(RColorBrewer::brewer.pal(10, "RdBu"))) 115 | 116 | # other display options 117 | col <- sapply(seq(0.1, 1, 0.1), function(x) adjustcolor("#1F78B4", x)) 118 | textplot_wordcloud(dfmat1, adjust = 0.5, random_order = FALSE, 119 | color = col, rotation = FALSE) 120 | 121 | # comparison plot of Obama v. Trump 122 | dfmat2 <- data_corpus_inaugural |> 123 | corpus_subset(President \%in\% c("Obama", "Trump")) |> 124 | tokens(remove_punct = TRUE) |> 125 | tokens_remove(stopwords("en")) |> 126 | dfm() 127 | dfmat2 <- dfm_group(dfmat2, dfmat2$President) |> 128 | dfm_trim(min_termfreq = 3) 129 | 130 | textplot_wordcloud(dfmat2, comparison = TRUE, max_words = 100, 131 | color = c("blue", "red")) 132 | 133 | \dontrun{ 134 | # for keyness 135 | tstat <- data_corpus_inaugural[c(1, 3)] |> 136 | tokens(remove_punct = TRUE) |> 137 | tokens_remove(stopwords("en")) |> 138 | dfm() |> 139 | quanteda.textstats::textstat_keyness() 140 | textplot_wordcloud(tstat, min_count = 2) 141 | textplot_wordcloud(tstat, min_count = 2, comparison = FALSE) 142 | } 143 | } 144 | \author{ 145 | Kohei Watanabe, building on code from Ian Fellows's \pkg{wordcloud} 146 | package. 147 | } 148 | \keyword{textplot} 149 | -------------------------------------------------------------------------------- /tests/testthat/test-textplot_network.R: -------------------------------------------------------------------------------- 1 | library("quanteda") 2 | 3 | test_that("test textplot_network", { 4 | #skip_on_os("linux") 5 | txt <- "A D A C E A D F E B A C E D" 6 | testfcm <- fcm(tokens(txt), context = "window", window = 3, tri = FALSE) 7 | testdfm <- dfm(tokens(txt)) 8 | expect_silent(textplot_network(testfcm, vertex_color = "red", offset = 0.1)) 9 | expect_silent(textplot_network(testdfm, offset = 0.1)) 10 | expect_error(textplot_network(testfcm, min_freq = 100), 11 | "There is no co-occurence higher than the threshold") 12 | 13 | # works with interger colour 14 | expect_silent(textplot_network(testfcm, vertex_color = 2)) 15 | expect_silent(textplot_network(testfcm, edge_color = 2)) 16 | }) 17 | 18 | test_that("test textplot_network works with vectorlized argument", { 19 | #skip_on_os("linux") 20 | txt <- "A D A C E A D F E B A C E D" 21 | 22 | testfcm <- fcm(tokens(txt), context = "window", window = 3, tri = FALSE) 23 | expect_silent(textplot_network(testfcm, vertex_color = rep(c(1, 2), nrow(testfcm) / 2))) 24 | expect_silent(textplot_network(testfcm, vertex_size = Matrix::rowSums(testfcm) / 5)) 25 | expect_silent(textplot_network(testfcm, vertex_labelcolor = rep(c(1, NA), nrow(testfcm) / 2))) 26 | expect_silent(textplot_network(testfcm, vertex_labelsize = Matrix::rowSums(testfcm) / 5)) 27 | }) 28 | 29 | test_that("textplot_network error when fcm is too large", { 30 | testdfm <- fcm(tokens(data_corpus_inaugural[1:5])) 31 | expect_error(textplot_network(testdfm, min_freq = 1, offset = 0, omit_isolated = FALSE), 32 | "fcm is too large for a network plot") 33 | }) 34 | 35 | test_that("test textplot_network font-selection", { 36 | skip_on_os("linux") 37 | txt <- tokens("A D A C E A D F E B A C E D") 38 | testfcm <- fcm(txt, context = "window", window = 3, tri = FALSE) 39 | testdfm <- dfm(txt) 40 | expect_silent(textplot_network(testfcm, offset = 0.1, 41 | vertex_labelfont = "serif")) 42 | expect_silent(textplot_network(testdfm, offset = 0.1, 43 | vertex_labelfont = "sans")) 44 | expect_silent(textplot_network(testfcm, min_freq = 0.1, 45 | vertex_labelfont = "not_a_real_font")) 46 | }) 47 | 48 | test_that("raises error when dfm is empty (#1419)", { 49 | mx <- dfm_trim(quanteda::data_dfm_lbgexample, 1000) 50 | expect_error(textplot_network(mx), 51 | quanteda.textplots:::message_error("dfm_empty")) 52 | expect_error(textplot_network(fcm(mx)), 53 | quanteda.textplots:::message_error("fcm_empty")) 54 | expect_error(textplot_wordcloud(mx), 55 | quanteda.textplots:::message_error("dfm_empty")) 56 | 57 | }) 58 | 59 | test_that("remove_edges is working", { 60 | mt <- fcm(tokens(c("a a b", "a b", "c b"))) 61 | expect_identical(colnames(quanteda.textplots:::remove_edges(mt, 1, TRUE)), 62 | c("a", "b", "c")) 63 | expect_identical(colnames(quanteda.textplots:::remove_edges(mt, 2, TRUE)), 64 | c("a", "b")) 65 | expect_equivalent(Matrix::diag(quanteda.textplots:::remove_edges(mt, 1, FALSE)), 66 | c(0, 0, 0)) 67 | }) 68 | 69 | # test_that("error when fcm is ordered", { 70 | # 71 | # mt <- fcm(c("a a b", "a b", "c b"), ordered = FALSE) 72 | # expect_silent(as.network(mt)) 73 | # mt2 <- fcm(c("a a b", "a b", "c b"), ordered = TRUE) 74 | # expect_error(as.network(mt2), 75 | # "Cannot plot ordered fcm") 76 | # }) 77 | 78 | test_that("as.network.fcm works", { 79 | txt <- tokens(c("a a a b b c", "a a c e", "a c e f g")) 80 | mat <- fcm(txt) 81 | net <- as.network(mat, min_freq = 1, omit_isolated = FALSE) 82 | expect_true(network::is.network(net)) 83 | expect_identical(network::network.vertex.names(net), featnames(mat)) 84 | expect_identical(network::get.vertex.attribute(net, "frequency"), 85 | unname(quanteda.textplots:::get_margin(mat))) 86 | expect_silent(as.network(mat, min_freq = 3, omit_isolated = TRUE)) 87 | }) 88 | 89 | test_that("as.network.fcm works with window", { 90 | txt <- tokens(c("a a a b b c", "a a c e", "a c e f g")) 91 | mat <- fcm(txt, contex = "window", window = 2) 92 | net <- as.network(mat, min_freq = 1, omit_isolated = FALSE) 93 | expect_true(network::is.network(net)) 94 | expect_identical(network::network.vertex.names(net), featnames(mat)) 95 | expect_identical(network::get.vertex.attribute(net, "frequency"), 96 | unname(quanteda.textplots:::get_margin(mat))) 97 | expect_silent(as.network(mat, min_freq = 3, omit_isolated = TRUE)) 98 | }) 99 | 100 | test_that("as.igraph.fcm works", { 101 | skip_if_not_installed("igraph") 102 | txt <- tokens(c("a a a b b c", "a a c e", "a c e f g")) 103 | mat <- fcm(txt) 104 | net <- as.igraph(mat, min_freq = 1, omit_isolated = FALSE) 105 | expect_true(igraph::is.igraph(net)) 106 | expect_identical(igraph::vertex_attr(net, "name"), featnames(mat)) 107 | expect_identical(igraph::vertex_attr(net, "frequency"), 108 | unname(quanteda.textplots:::get_margin(mat))) 109 | expect_silent(as.igraph(mat, min_freq = 3, omit_isolated = TRUE)) 110 | }) 111 | 112 | test_that("as.igraph.fcm works with window", { 113 | skip_if_not_installed("igraph") 114 | skip_on_os("linux") 115 | txt <- tokens(c("a a a b b c", "a a c e", "a c e f g")) 116 | mat <- fcm(txt, contex = "window", window = 2) 117 | net <- as.igraph(mat, min_freq = 1, omit_isolated = FALSE) 118 | expect_true(igraph::is.igraph(net)) 119 | expect_identical(igraph::vertex_attr(net, "name"), featnames(mat)) 120 | expect_identical(igraph::vertex_attr(net, "frequency"), 121 | unname(quanteda.textplots:::get_margin(mat))) 122 | expect_silent(as.igraph(mat, min_freq = 3, omit_isolated = TRUE)) 123 | }) 124 | -------------------------------------------------------------------------------- /R/textplot_keyness.R: -------------------------------------------------------------------------------- 1 | #' Plot word keyness 2 | #' 3 | #' Plot the results of a "keyword" of features comparing their differential 4 | #' associations with a target and a reference group, after calculating keyness 5 | #' using [quanteda.textstats::textstat_keyness()]. 6 | #' @param x a return object from [quanteda.textstats::textstat_keyness()] 7 | #' @param show_reference logical; if `TRUE`, show key reference features in 8 | #' addition to key target features 9 | #' @param show_legend logical; if `TRUE`, show legend 10 | #' @param n integer; number of features to plot 11 | #' @param min_count numeric; minimum total count of feature across the target 12 | #' and reference categories, for a feature to be included in the plot 13 | #' @param margin numeric; size of margin where feature labels are shown 14 | #' @param color character or integer; colours of bars for target and reference 15 | #' documents. `color` must have two elements when `show_reference = TRUE`. 16 | #' See \link[ggplot2:aes_colour_fill_alpha]{ggplot2::color}. 17 | #' @param labelcolor character; color of feature labels. 18 | #' @param labelsize numeric; size of feature labels and bars. See 19 | #' \link[ggplot2:aes_linetype_size_shape]{ggplot2::size}. 20 | #' @param font character; font-family of texts. Use default font if `NULL`. 21 | #' @return a \pkg{ggplot2} object 22 | #' @export 23 | #' @author Haiyan Wang and Kohei Watanabe 24 | #' @seealso [quanteda.textstats::textstat_keyness()] 25 | #' @keywords textplot 26 | #' @examples 27 | #' \dontrun{ 28 | #' library("quanteda") 29 | #' # compare Trump speeches to other Presidents by chi^2 30 | #' dfmat1 <- data_corpus_inaugural |> 31 | #' corpus_subset(Year > 1980) |> 32 | #' tokens(remove_punct = TRUE) |> 33 | #' tokens_remove(stopwords("en")) |> 34 | #' dfm() 35 | #' dfmat1 <- dfm_group(dfmat1, groups = dfmat1$President) 36 | #' tstat1 <- quanteda.textstats::textstat_keyness(dfmat1, target = "Trump") 37 | #' textplot_keyness(tstat1, margin = 0.2, n = 10) 38 | #' tstat1 <- quanteda.textstats::textstat_keyness(dfmat1, target = "Trump") 39 | #' textplot_keyness(tstat1, margin = 0.2, n = 10) 40 | #' 41 | #' # compare contemporary Democrats v. Republicans 42 | #' corp <- data_corpus_inaugural |> 43 | #' corpus_subset(Year > 1960) 44 | #' corp$party <- ifelse(docvars(corp, "President") %in% c("Nixon", "Reagan", "Bush", "Trump"), 45 | #' "Republican", "Democrat") 46 | #' dfmat2 <- corp |> 47 | #' tokens(remove_punct = TRUE) |> 48 | #' tokens_remove(stopwords("en")) |> 49 | #' dfm() 50 | #' tstat2 <- quanteda.textstats::textstat_keyness(dfm_group(dfmat2, groups = dfmat2$party), 51 | #' target = "Democrat", measure = "lr") 52 | #' textplot_keyness(tstat2, color = c("blue", "red"), n = 10) 53 | #' } 54 | textplot_keyness <- function(x, show_reference = TRUE, show_legend = TRUE, 55 | n = 20L, min_count = 2L, margin = 0.05, 56 | color = c("darkblue", "gray"), labelcolor = "gray30", 57 | labelsize = 4, font = NULL) { 58 | UseMethod("textplot_keyness") 59 | } 60 | 61 | #' @export 62 | textplot_keyness.default <- function(x, show_reference = TRUE, show_legend = TRUE, 63 | n = 20L, min_count = 2L, margin = 0.05, 64 | color = c("darkblue", "gray"), labelcolor = "gray30", 65 | labelsize = 4, font = NULL) { 66 | stop(friendly_class_undefined_message(class(x), "textplot_keyness")) 67 | } 68 | 69 | #' @import ggplot2 70 | #' @importFrom utils head tail 71 | #' @export 72 | textplot_keyness.keyness <- function(x, show_reference = TRUE, show_legend = TRUE, 73 | n = 20L, min_count = 2L, margin = 0.05, 74 | color = c("darkblue", "gray"), labelcolor = "gray30", 75 | labelsize = 4, font = NULL) { 76 | 77 | font <- check_font(font) 78 | color <- as.factor(color) 79 | if (show_reference) { 80 | if (length(color) > 2) { 81 | color <- color[1:2] 82 | } else if (length(color) == 1) { 83 | color <- rep(color, 2) 84 | } 85 | } 86 | 87 | # extract attribute befor subsetting 88 | measure <- colnames(x)[2] 89 | 90 | # drop infrequent words 91 | data <- x[(x$n_target + x$n_reference) >= min_count, , drop = FALSE] 92 | 93 | if (nrow(data) < 1) 94 | stop("Too few words in the documents.") 95 | 96 | data$keyness <- data[[2]] 97 | data$right <- data$keyness >= 0 98 | if (show_reference) { 99 | t <- intersect(which(data$right), head(seq(nrow(data)), n)) 100 | r <- intersect(which(!data$right), tail(seq(nrow(data)), n)) 101 | i <- union(t, r) 102 | } else { 103 | i <- intersect(which(data$right), head(seq(nrow(data)), n)) 104 | } 105 | data <- data[i, , drop = FALSE] 106 | if (show_reference) { 107 | group <- attr(x, "groups") 108 | data$color <- color[2 - data$right] 109 | } else { 110 | data$color <- color[1] 111 | color <- group <- NULL 112 | } 113 | 114 | data$x1 <- ifelse(data$right, abs(data$keyness), abs(data$keyness) * -1) 115 | data$y1 <- rank(data$keyness, ties.method = "first") 116 | data$x2 <- 0 117 | data$y2 <- data$y 118 | margin <- margin * max(abs(data$x1)) * 2 119 | 120 | x1 <- y1 <- x2 <- y2 <- feature <- NULL 121 | ggplot(data) + 122 | xlim(if (show_reference) min(data$x1) - margin else 0, max(data$x1) + margin) + 123 | geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2, color = color), 124 | linewidth = labelsize) + 125 | scale_colour_identity(NULL, labels = group, breaks = color, 126 | guide = if (show_legend) "legend" else FALSE) + 127 | xlab(measure) + 128 | geom_label(aes(x = x1, y = y1, label = feature), label.size = NA, fill = NA, 129 | vjust = "center", hjust = ifelse(data$right, "left", "right"), 130 | color = labelcolor, size = labelsize, family = font) + 131 | theme_bw(base_family = font) + 132 | theme(axis.line = element_blank(), 133 | axis.title.y = element_blank(), 134 | axis.text.y = element_blank(), 135 | axis.ticks.y = element_blank(), 136 | plot.background = element_blank(), 137 | panel.grid.major.y = element_line(linetype = "dotted")) 138 | } 139 | -------------------------------------------------------------------------------- /R/textplot_xray.R: -------------------------------------------------------------------------------- 1 | #' Plot the dispersion of key word(s) 2 | #' 3 | #' Plots a dispersion or "x-ray" plot of selected word pattern(s) across one or 4 | #' more texts. The format of the plot depends on the number of 5 | #' [kwic][quanteda::kwic] class objects passed: if there is only one document, 6 | #' keywords are plotted one below the other. If there are multiple documents the 7 | #' documents are plotted one below the other, with keywords shown side-by-side. 8 | #' Given that this returns a \pkg{ggplot2} object, you can modify the plot by 9 | #' adding \pkg{ggplot2} layers (see example). 10 | #' @param ... any number of [kwic][quanteda::kwic] class objects 11 | #' @param scale `"relative"` or `"absolute"`: whether to scale the token index 12 | #' axis by absolute position of the token in the document or by relative 13 | #' position. Defaults are `"absolute"` for single document and `"relative"` 14 | #' for multiple documents. 15 | #' @param sort whether to sort the rows of a multiple document plot by document 16 | #' name 17 | #' @return a \pkg{ggplot2} object 18 | #' @section Known Issues: 19 | #' These are known issues on which we are working to solve in future versions: 20 | #' * `textplot_xray()` will not display the patterns correctly when 21 | #' these are multi-token sequences. 22 | #' * For dictionaries with keys that have overlapping value matches to tokens in 23 | #' the text, only the first match will be used in the plot. The way around this 24 | #' is to produce one kwic per dictionary key, and send them as a list to 25 | #' `textplot_xray`. 26 | #' @examples 27 | #' library("quanteda") 28 | #' toks <- data_corpus_inaugural |> 29 | #' corpus_subset(Year > 1970) |> 30 | #' tokens() 31 | #' # compare multiple documents 32 | #' textplot_xray(kwic(toks, pattern = "american")) 33 | #' textplot_xray(kwic(toks, pattern = "american"), scale = "absolute") 34 | #' 35 | #' # compare multiple terms across multiple documents 36 | #' textplot_xray(kwic(toks, pattern = "america*"), 37 | #' kwic(toks, pattern = "people")) 38 | #' 39 | #' \dontrun{ 40 | #' # how to modify the ggplot with different options 41 | #' library("ggplot2") 42 | #' tplot <- textplot_xray(kwic(toks, pattern = "american"), 43 | #' kwic(toks, pattern = "people")) 44 | #' tplot + aes(color = keyword) + scale_color_manual(values = c('red', 'blue')) 45 | #' 46 | #' # adjust the names of the document names 47 | #' docnames(toks) <- apply(docvars(toks, c("Year", "President")), 1, paste, collapse = ", ") 48 | #' textplot_xray(kwic(toks, pattern = "america*"), 49 | #' kwic(toks, pattern = "people")) 50 | #' } 51 | #' @export 52 | #' @keywords textplot 53 | textplot_xray <- function(..., scale = c("absolute", "relative"), 54 | sort = FALSE) { 55 | UseMethod("textplot_xray") 56 | } 57 | 58 | #' @export 59 | textplot_xray.default <- function(..., scale = c("absolute", "relative"), 60 | sort = FALSE) { 61 | stop(friendly_class_undefined_message(..., "textplot_xray")) 62 | } 63 | 64 | #' @importFrom quanteda is.kwic ntoken 65 | #' @export 66 | textplot_xray.kwic <- function(..., scale = c("absolute", "relative"), 67 | sort = FALSE) { 68 | kwics <- list(...) 69 | if (!all(vapply(kwics, is.kwic, logical(1)))) 70 | stop("objects to plot must be kwic objects") 71 | 72 | # create a single data.frame from kwics 73 | x <- do.call(rbind, lapply(kwics, as.data.frame)) 74 | 75 | # get the vector of ntokens 76 | ntokensbydoc <- if (is.null(attr(kwics[[1]], "ntoken"))) { 77 | # if v3 78 | unlist(lapply(kwics, function(y) ntoken(attr(y, "tokens")))) 79 | } else { 80 | # if pre-v3 81 | unlist(lapply(kwics, attr, "ntoken")) 82 | } 83 | x$ntokens <- ntokensbydoc[x$docname] 84 | 85 | # replace "found" keyword with patterned keyword 86 | x$keyword <- unlist(lapply(kwics, function(l) l[["pattern"]])) 87 | 88 | 89 | multiple_documents <- length(unique(x$docname)) > 1 90 | 91 | # Deal with the scale argument: 92 | # if there is a user-supplied value, use that after passing through 93 | # match.arg; if not, use relative for multiple documents and absolute 94 | # for single documents 95 | if (!missing(scale)) { 96 | scale <- match.arg(scale) 97 | } 98 | else { 99 | if (multiple_documents) { 100 | scale <- "relative" 101 | } else { 102 | scale <- "absolute" 103 | } 104 | } 105 | 106 | # Deal with the sort argument: 107 | x$docname <- if (sort) { 108 | factor(x$docname) # levels are sorted by default 109 | } else { 110 | factor(x$docname, levels = unique(x$docname)) 111 | } 112 | 113 | if (scale == "relative") 114 | x$from <- x$from / x$ntokens 115 | 116 | from <- ntokens <- NULL 117 | max_ntokens <- max(x$ntokens) 118 | plot <- ggplot2::ggplot(x, ggplot2::aes(x = from, y = 1)) + 119 | ggplot2::geom_segment(ggplot2::aes(xend = from, yend = 0)) + 120 | ggplot2::theme(axis.line = ggplot2::element_blank(), 121 | panel.background = ggplot2::element_blank(), 122 | panel.grid.major.y = ggplot2::element_blank(), 123 | panel.grid.minor.y = ggplot2::element_blank(), 124 | plot.background = ggplot2::element_blank(), 125 | axis.ticks.y = ggplot2::element_blank(), 126 | axis.text.y = ggplot2::element_blank(), 127 | panel.spacing = grid::unit(0.1, "lines"), 128 | panel.border = ggplot2::element_rect(colour = "gray", fill = NA), 129 | strip.text.y = ggplot2::element_text(angle = 0) 130 | ) 131 | 132 | if (scale == "absolute") 133 | plot <- plot + 134 | ggplot2::geom_rect(ggplot2::aes(xmin = ntokens, xmax = max_ntokens, 135 | ymin = 0, ymax = 1), fill = "gray90") 136 | 137 | if (multiple_documents) { 138 | # If there is more than one document, put documents on the panel y-axis 139 | # and keyword(s) on the panel x-axis 140 | plot <- plot + ggplot2::facet_grid(docname ~ keyword) + 141 | ggplot2::labs(y = "Document", title = paste("Lexical dispersion plot")) 142 | } 143 | else { 144 | # If not, put keywords on the panel y-axis and the doc name in the title 145 | plot <- plot + ggplot2::facet_grid(keyword~.) + 146 | ggplot2::labs(y = "", title = paste("Lexical dispersion plot, document:", 147 | x$docname[[1]])) 148 | } 149 | 150 | if (scale == "relative") { 151 | plot <- plot + ggplot2::labs(x = "Relative token index") 152 | } 153 | else { 154 | plot <- plot + ggplot2::labs(x = "Token index") 155 | } 156 | 157 | plot 158 | } 159 | -------------------------------------------------------------------------------- /tests/testthat/test-textplot_xray.R: -------------------------------------------------------------------------------- 1 | library("quanteda") 2 | 3 | pdf(file = tempfile(".pdf"), width = 10, height = 10) 4 | 5 | test_that("test plot.kwic scale argument default", { 6 | sda <- kwic(tokens(data_corpus_inaugural[[1]]), "american") 7 | sdp <- kwic(tokens(data_corpus_inaugural[[1]]), "people") 8 | mda <- kwic(tokens(data_corpus_inaugural), "american") 9 | mdp <- kwic(tokens(data_corpus_inaugural), "people") 10 | 11 | # Single document, should be absolute 12 | p <- textplot_xray(sda) 13 | expect_equal(p$labels$x, "Token index") 14 | 15 | # Single document, multiple keywords, should be absolute 16 | p <- textplot_xray(sda, sdp) 17 | expect_equal(p$labels$x, "Token index") 18 | 19 | # Multiple documents, should be relative 20 | p <- textplot_xray(mda) 21 | expect_equal(p$labels$x, "Relative token index") 22 | 23 | # Multiple documents, multiple keywords, should be relative 24 | p <- textplot_xray(mda, mdp) 25 | expect_equal(p$labels$x, "Relative token index") 26 | 27 | # Explicit overrides 28 | p <- textplot_xray(sda, scale = "absolute") 29 | expect_equal(p$labels$x, "Token index") 30 | p <- textplot_xray(sda, sdp, scale = "absolute") 31 | expect_equal(p$labels$x, "Token index") 32 | p <- textplot_xray(mda, scale = "absolute") 33 | expect_equal(p$labels$x, "Token index") 34 | p <- textplot_xray(mda, mdp, scale = "absolute") 35 | expect_equal(p$labels$x, "Token index") 36 | 37 | p <- textplot_xray(sda, scale = "relative") 38 | expect_equal(p$labels$x, "Relative token index") 39 | p <- textplot_xray(sda, sdp, scale = "relative") 40 | expect_equal(p$labels$x, "Relative token index") 41 | p <- textplot_xray(mda, scale = "relative") 42 | expect_equal(p$labels$x, "Relative token index") 43 | p <- textplot_xray(mda, mdp, scale = "relative") 44 | expect_equal(p$labels$x, "Relative token index") 45 | }) 46 | 47 | test_that("test plot.kwic facet order parameter", { 48 | p <- textplot_xray(kwic(tokens(data_corpus_inaugural), "american"), sort = TRUE) 49 | plot_docnames <- as.character(unique(ggplot2::ggplot_build(p)$layout$panel_layout$docname)) 50 | if (identical(plot_docnames, character(0))) { 51 | plot_docnames <- as.character(unique(ggplot2::ggplot_build(p)$layout$layout$docname)) 52 | } 53 | expect_true( 54 | all( 55 | plot_docnames[order(plot_docnames)] == plot_docnames 56 | ) 57 | ) 58 | p <- textplot_xray(kwic(tokens(data_corpus_inaugural), "american"), 59 | kwic(tokens(data_corpus_inaugural), "people"), 60 | sort = TRUE) 61 | plot_docnames <- as.character(unique(ggplot2::ggplot_build(p)$layout$panel_layout$docname)) 62 | if (identical(plot_docnames, character(0))) { 63 | plot_docnames <- as.character(unique(ggplot2::ggplot_build(p)$layout$layout$docname)) 64 | } 65 | expect_true( 66 | all( 67 | plot_docnames[order(plot_docnames)] == plot_docnames 68 | ) 69 | ) 70 | 71 | # Default should be false 72 | p <- textplot_xray(kwic(tokens(data_corpus_inaugural[c(53:54, 1:2)]), "american"), 73 | kwic(tokens(data_corpus_inaugural[c(53:54, 1:2)]), "people")) 74 | plot_docnames <- as.character(unique(ggplot2::ggplot_build(p)$layout$panel_layout$docname)) 75 | if (identical(plot_docnames, character(0))) { 76 | plot_docnames <- as.character(unique(ggplot2::ggplot_build(p)$layout$layout$docname)) 77 | } 78 | expect_false( 79 | all( 80 | plot_docnames[order(plot_docnames)] == plot_docnames 81 | ) 82 | ) 83 | }) 84 | 85 | # test_that("test plot.kwic keeps order of keywords passed", { 86 | # p <- textplot_xray(kwic(data_corpus_inaugural, "people"), 87 | # kwic(data_corpus_inaugural, "american"), sort = TRUE) 88 | # keywords <- as.character(unique(ggplot2::ggplot_build(p)$layout$panel_layout$keyword)) 89 | # if (identical(keywords, character(0))) { 90 | # keywords <- as.character(unique(ggplot2::ggplot_build(p)$layout$layout$keyword)) 91 | # } 92 | # expect_equal( 93 | # keywords, 94 | # c("people", "american") 95 | # ) 96 | # }) 97 | 98 | test_that("multiple patterns display correctly in textplot_kwic", { 99 | skip("For interactive visual inspection only") 100 | toks <- tokens(c(alpha1 = paste(letters, collapse = " "), 101 | alpha2 = paste(LETTERS, collapse = " "))) 102 | 103 | kwic_char_f <- kwic(toks, "f", window = 3) 104 | kwic_char_u <- kwic(toks, "u", window = 3) 105 | kwic_char_uf <- kwic(toks, c("u", "f"), window = 3) 106 | kwic_char_fu <- kwic(toks, c("f", "u"), window = 3) 107 | kwic_dict_u <- kwic(toks, dictionary(list(ukey = "u")), window = 3) 108 | kwic_dict_f <- kwic(toks, dictionary(list(fkey = "f")), window = 3) 109 | kwic_dict_uf <- kwic(toks, dictionary(list(ukey = "u", fkey = "f")), window = 3) 110 | kwic_dict_fu <- kwic(toks, dictionary(list(fkey = "f", ukey = "u")), window = 3) 111 | kwic_dict_uf_jm <- kwic(toks, dictionary(list(ufkey = c("u", "f"), 112 | jmkey = c("j", "m"))), window = 3) 113 | 114 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 115 | textplot_xray(kwic_char_f, scale = "absolute") 116 | 117 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 118 | textplot_xray(kwic_char_u, scale = "absolute") 119 | 120 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 121 | textplot_xray(kwic_char_u, kwic_char_f, scale = "absolute") 122 | 123 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 124 | textplot_xray(kwic_dict_f, scale = "absolute") 125 | 126 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 127 | textplot_xray(kwic_dict_u, scale = "absolute") 128 | 129 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 130 | textplot_xray(kwic_dict_u, kwic_dict_f, scale = "absolute") 131 | 132 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 133 | textplot_xray(kwic_dict_f, kwic_dict_u, scale = "absolute") 134 | 135 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 136 | textplot_xray(kwic_dict_uf, scale = "absolute") 137 | 138 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 139 | textplot_xray(kwic_dict_fu, scale = "absolute") 140 | 141 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 142 | textplot_xray(kwic_char_uf, scale = "absolute") 143 | 144 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 145 | textplot_xray(kwic_char_fu, scale = "absolute") 146 | 147 | # warning free: ✓ label order correct: ✓ plot order correct: ✓ 148 | textplot_xray(kwic_dict_uf_jm, scale = "absolute") 149 | }) 150 | 151 | test_that("phrasal patterns display correctly in textplot_kwic", { 152 | skip("For interactive visual inspection only") 153 | toks <- tokens(c(alpha1 = paste(letters, collapse = " "), 154 | alpha2 = paste(LETTERS, collapse = " "))) 155 | 156 | kwic_char_bc <- kwic(toks, phrase("b c"), window = 3) 157 | kwic_dict_bc <- kwic(toks, dictionary(list(bc = "b c")), window = 3) 158 | kwic_list_bc <- kwic(toks, list(bc = c("b", "c")), window = 3) 159 | 160 | # label OK: ✓ label order correct: ✓ plot order correct: ✓ 161 | textplot_xray(kwic_char_bc, scale = "absolute") 162 | # label OK: ✓ label order correct: ✓ plot order correct: ✓ 163 | textplot_xray(kwic_dict_bc, scale = "absolute") 164 | # label OK: ✓ label order correct: ✓ plot order correct: ✓ 165 | textplot_xray(kwic_list_bc, scale = "absolute") 166 | }) 167 | 168 | test_that("textplot_xray works with new kwic, one token phrase", { 169 | data_corpus_inauguralpost70 <- corpus_subset(data_corpus_inaugural, Year > 1970) 170 | knew <- kwic(tokens(data_corpus_inauguralpost70), "american") 171 | expect_silent(textplot_xray(knew)) 172 | }) 173 | 174 | test_that("textplot_xray works with new kwic, two token phrase", { 175 | data_corpus_inauguralpost70 <- corpus_subset(data_corpus_inaugural, Year > 1970) 176 | knew <- kwic(tokens(data_corpus_inauguralpost70), phrase("american people")) 177 | expect_silent(textplot_xray(knew)) 178 | }) 179 | 180 | dev.off() 181 | -------------------------------------------------------------------------------- /R/textplot_network.R: -------------------------------------------------------------------------------- 1 | #' Plot a network of feature co-occurrences 2 | #' 3 | #' Plot an [fcm][quanteda::fcm] object as a network, where edges show 4 | #' co-occurrences of features. 5 | #' @param x a [fcm][quanteda::fcm] or [dfm][quanteda::dfm] object 6 | #' @param min_freq a frequency count threshold or proportion for co-occurrence 7 | #' frequencies of features to be included. 8 | #' @param omit_isolated if `TRUE`, features do not occur more frequent than 9 | #' `min_freq` will be omitted. 10 | #' @param edge_color colour of edges that connect vertices. 11 | #' @param edge_alpha opacity of edges ranging from 0 to 1.0. 12 | #' @param edge_size size of edges for most frequent co-occurrence The size of 13 | #' other edges are determined proportionally to the 99th percentile frequency 14 | #' instead of the maximum to reduce the impact of outliers. 15 | #' @param vertex_size size of vertices 16 | #' @param vertex_color colour of vertices. 17 | #' @param vertex_labelcolor colour of texts. Defaults to the same as 18 | #' `vertex_color`. If `NA` is given, texts are not rendered. 19 | #' @param vertex_labelfont font-family of texts. Use default font if 20 | #' `NULL`. 21 | #' @param vertex_labelsize size of vertex labels in mm. Defaults to size 5. 22 | #' Supports both integer values and vector values. 23 | #' @param offset if `NULL`, the distance between vertices and texts are 24 | #' determined automatically. 25 | #' @param ... additional arguments passed to [network][network::network] or 26 | #' [graph_from_adjacency_matrix][igraph::graph_from_adjacency_matrix]. Not 27 | #' used for `as.igraph`. 28 | #' @details Currently the size of the network is limited to 1000, because of the 29 | #' computationally intensive nature of network formation for larger matrices. 30 | #' When the [fcm][quanteda::fcm] is large, users should select features using 31 | #' [fcm_select()][quanteda::fcm_select], set the threshold using `min_freq`, 32 | #' or implement own plotting function using [`as.network()`][as.network.fcm]. 33 | #' @author Kohei Watanabe and Stefan Müller 34 | #' @examples 35 | #' set.seed(100) 36 | #' library("quanteda") 37 | #' toks <- data_char_ukimmig2010 |> 38 | #' tokens(remove_punct = TRUE) |> 39 | #' tokens_tolower() |> 40 | #' tokens_remove(pattern = stopwords("english"), padding = FALSE) 41 | #' fcmat <- fcm(toks, context = "window", tri = FALSE) 42 | #' feat <- colSums(fcmat) |> 43 | #' sort(decreasing = TRUE) |> 44 | #' head(30) |> 45 | #' names() 46 | #' fcm_select(fcmat, pattern = feat) |> 47 | #' textplot_network(min_freq = 0.5) 48 | #' fcm_select(fcmat, pattern = feat) |> 49 | #' textplot_network(min_freq = 0.8) 50 | #' fcm_select(fcmat, pattern = feat) |> 51 | #' textplot_network(min_freq = 0.8, vertex_labelcolor = rep(c('gray40', NA), 15)) 52 | #' fcm_select(fcmat, pattern = feat) |> 53 | #' textplot_network(vertex_labelsize = 10) 54 | #' fcm_30 <- fcm_select(fcmat, pattern = feat) 55 | #' textplot_network(fcm_30, 56 | #' vertex_labelsize = Matrix::rowSums(fcm_30) / min(Matrix::rowSums(fcm_30))) 57 | #' # Vector inputs to vertex_labelsize can be scaled if too small / large 58 | #' textplot_network(fcm_30, 59 | #' vertex_labelsize = 1.5 * Matrix::rowSums(fcm_30) / 60 | #' min(Matrix::rowSums(fcm_30))) 61 | #' @export 62 | #' @seealso [fcm][quanteda::fcm()] 63 | #' @import ggplot2 64 | #' @keywords textplot 65 | textplot_network <- function(x, min_freq = 0.5, omit_isolated = TRUE, 66 | edge_color = "#1F78B4", edge_alpha = 0.5, 67 | edge_size = 2, 68 | vertex_color = "#4D4D4D", vertex_size = 2, 69 | vertex_labelcolor = NULL, 70 | vertex_labelfont = NULL, 71 | vertex_labelsize = 5, 72 | offset = NULL, ...) { 73 | UseMethod("textplot_network") 74 | } 75 | 76 | #' @export 77 | #' @importFrom quanteda fcm 78 | textplot_network.dfm <- function(x, min_freq = 0.5, omit_isolated = TRUE, 79 | edge_color = "#1F78B4", edge_alpha = 0.5, 80 | edge_size = 2, 81 | vertex_color = "#4D4D4D", vertex_size = 2, 82 | vertex_labelcolor = NULL, 83 | vertex_labelfont = NULL, 84 | vertex_labelsize = 5, 85 | offset = NULL, ...) { 86 | 87 | if (!sum(x)) stop(message_error("dfm_empty")) 88 | textplot_network(fcm(x), min_freq = min_freq, omit_isolated = omit_isolated, 89 | edge_color = edge_color, edge_alpha = edge_alpha, 90 | edge_size = edge_size, 91 | vertex_color = vertex_color, vertex_size = vertex_size, 92 | vertex_labelcolor = vertex_labelcolor, 93 | vertex_labelfont = vertex_labelfont, 94 | vertex_labelsize = vertex_labelsize, 95 | offset = NULL, ...) 96 | } 97 | 98 | 99 | #' @export 100 | #' @importFrom stats quantile 101 | #' @importFrom quanteda featnames 102 | textplot_network.fcm <- function(x, min_freq = 0.5, omit_isolated = TRUE, 103 | edge_color = "#1F78B4", edge_alpha = 0.5, 104 | edge_size = 2, 105 | vertex_color = "#4D4D4D", vertex_size = 2, 106 | vertex_labelcolor = NULL, 107 | vertex_labelfont = NULL, 108 | vertex_labelsize = 5, 109 | offset = NULL, 110 | ...) { 111 | 112 | if (!sum(x)) stop(message_error("fcm_empty")) 113 | font <- check_font(vertex_labelfont) 114 | net <- as.network(x, min_freq = min_freq, omit_isolated = omit_isolated, ...) 115 | 116 | vertex <- data.frame(sna::gplot.layout.fruchtermanreingold(net, NULL)) 117 | colnames(vertex) <- c("x", "y") 118 | vertex$label <- network::network.vertex.names(net) 119 | 120 | weight <- network::get.edge.attribute(net, "weight") 121 | weight <- weight / quantile(weight, 0.99) 122 | # weight <- weight / mean(tail(sort(weight), 10)) 123 | 124 | index <- network::as.edgelist(net) 125 | edge <- data.frame(x1 = vertex[, 1][index[, 1]], 126 | y1 = vertex[, 2][index[, 1]], 127 | x2 = vertex[, 1][index[, 2]], 128 | y2 = vertex[, 2][index[, 2]], 129 | weight = weight) 130 | 131 | if (is.null(vertex_labelcolor)) 132 | vertex_labelcolor <- vertex_color 133 | 134 | # drop colours of omitted vertices 135 | l <- featnames(x) %in% network::network.vertex.names(net) 136 | if (length(vertex_labelcolor) > 1) vertex_labelcolor <- vertex_labelcolor[l] 137 | if (length(vertex_color) > 1) vertex_color <- vertex_color[l] 138 | if (length(vertex_size) > 1) vertex_size <- vertex_size[l] 139 | if (length(vertex_labelsize) > 1) vertex_labelsize <- vertex_labelsize[l] 140 | 141 | edge$color <- edge_color 142 | edge$alpha <- edge_alpha 143 | edge$size <- edge_size 144 | vertex$color <- vertex_color 145 | vertex$size <- vertex_size 146 | vertex$labelcolor <- vertex_labelcolor 147 | vertex$labelsize <- vertex_labelsize 148 | 149 | plot_network(edge, vertex, font, offset) 150 | } 151 | 152 | 153 | 154 | # as.network ---------- 155 | 156 | #' redefinition of network::as.network() 157 | #' @param x input object 158 | #' @param ... additional arguments 159 | #' @keywords internal 160 | #' @export 161 | as.network <- function(x, ...) { 162 | UseMethod("as.network") 163 | } 164 | 165 | #' @export 166 | as.network.default <- function(x, ...) { 167 | network::as.network(x, ...) 168 | } 169 | 170 | #' @rdname textplot_network 171 | #' @importFrom quanteda nfeat meta 172 | #' @method as.network fcm 173 | #' @importFrom methods .hasSlot 174 | #' @export 175 | #' @seealso [network::network()] 176 | as.network.fcm <- function(x, min_freq = 0.5, omit_isolated = TRUE, ...) { 177 | 178 | if (nfeat(x) > 1000) stop("fcm is too large for a network plot") 179 | f <- get_margin(x) 180 | x <- remove_edges(x, min_freq, omit_isolated) 181 | x <- network::network(as.matrix(x), matrix.type = "adjacency", directed = FALSE, 182 | ignore.eval = FALSE, names.eval = "weight", ...) 183 | network::set.vertex.attribute(x, "frequency", f[network::network.vertex.names(x)]) 184 | } 185 | 186 | # as.igraph ---------- 187 | 188 | #' Convert an fcm to an igraph object 189 | #' 190 | #' Convert an [fcm][quanteda::fcm] object to an \pkg{igraph} graph object. 191 | #' @keywords internal 192 | #' @export 193 | as.igraph <- function(x, ...) UseMethod("as.igraph") 194 | 195 | #' @rdname textplot_network 196 | #' @method as.igraph fcm 197 | #' @export 198 | #' @seealso [igraph::graph_from_adjacency_matrix()] 199 | #' @examples 200 | #' 201 | #' # as.igraph 202 | #' if (requireNamespace("igraph", quietly = TRUE)) { 203 | #' txt <- c("a a a b b c", "a a c e", "a c e f g") 204 | #' mat <- fcm(tokens(txt)) 205 | #' as.igraph(mat, min_freq = 1, omit_isolated = FALSE) 206 | #' } 207 | as.igraph.fcm <- function(x, min_freq = 0.5, omit_isolated = TRUE, ...) { 208 | f <- get_margin(x) 209 | x <- remove_edges(x, min_freq, omit_isolated) 210 | x <- igraph::graph_from_adjacency_matrix(x, ...) 211 | igraph::set_vertex_attr(x, "frequency", value = f[igraph::vertex_attr(x, "name")]) 212 | } 213 | 214 | # internal ---------- 215 | 216 | # return the slot "margin" or get from object meta for quanteda >= v3 217 | get_margin <- function(x) { 218 | if (.hasSlot(x, "margin")) { 219 | # pre-v3 220 | x@margin 221 | } else { 222 | # quanteda >= v3 223 | meta(x, "margin", type = "object") 224 | } 225 | } 226 | 227 | remove_edges <- function(x, min_freq, omit_isolated) { 228 | Matrix::diag(x) <- 0 229 | x <- methods::as(x, "TsparseMatrix") 230 | 231 | # drop weak edges 232 | if (min_freq > 0) { 233 | if (min_freq < 1) { 234 | min_freq <- stats::quantile(x@x, min_freq) 235 | } 236 | l <- x@x >= min_freq 237 | x@i <- x@i[l] 238 | x@j <- x@j[l] 239 | x@x <- x@x[l] 240 | } 241 | 242 | # drop isolated vertices 243 | if (omit_isolated) { 244 | l <- Matrix::colSums(x) != 0 | Matrix::rowSums(x) != 0 245 | x <- x[l, l, drop = FALSE] 246 | } 247 | 248 | if (length(x@x) == 0 || all(x@x == 0)) 249 | stop("There is no co-occurence higher than the threshold") 250 | 251 | return(x) 252 | } 253 | 254 | plot_network <- function(edge, vertex, font, offset) { 255 | x <- NULL 256 | label <- x1 <- x2 <- y <- y1 <- y2 <- NULL 257 | 258 | plot <- ggplot() + 259 | geom_curve(data = edge, aes(x = x1, y = y1, xend = x2, yend = y2), 260 | color = edge$color, curvature = 0.2, 261 | alpha = edge$alpha, lineend = "round", 262 | linewidth = edge$weight * edge$size, 263 | angle = 90) + 264 | geom_point(data = vertex, aes(x, y), color = vertex$color, 265 | size = vertex$size, shape = 19) 266 | 267 | if (is.null(offset)) { 268 | plot <- plot + 269 | ggrepel::geom_text_repel(data = vertex, 270 | aes(x, y, label = label), 271 | segment.color = vertex$color, 272 | segment.size = 0.2, 273 | color = vertex$labelcolor, 274 | family = font, 275 | size = vertex$labelsize) 276 | } else { 277 | plot <- plot + 278 | geom_text(data = vertex, aes(x, y, label = label), 279 | nudge_y = offset, 280 | color = vertex$labelcolor, 281 | family = font, 282 | size = vertex$labelsize) 283 | } 284 | 285 | plot <- plot + 286 | scale_x_continuous(breaks = NULL) + 287 | scale_y_continuous(breaks = NULL) + 288 | theme_void(base_family = font) + 289 | theme( 290 | plot.margin = margin(0, 0, 0, 0), 291 | panel.background = element_blank(), 292 | axis.title.x = element_blank(), 293 | axis.title.y = element_blank(), 294 | legend.position = "none", 295 | panel.grid.minor = element_blank(), 296 | panel.grid.major = element_blank()) 297 | 298 | return(plot) 299 | } 300 | -------------------------------------------------------------------------------- /R/textplot_scale1d.R: -------------------------------------------------------------------------------- 1 | #' Plot a fitted scaling model 2 | #' 3 | #' Plot the results of a fitted scaling model, from (e.g.) a predicted 4 | #' [quanteda.textmodels::textmodel_wordscores] model or a fitted 5 | #' [quanteda.textmodels::textmodel_wordfish] or 6 | #' [quanteda.textmodels::textmodel_ca] model. Either document or feature 7 | #' parameters may be plotted: an ideal point-style plot (estimated document 8 | #' position plus confidence interval on the x-axis, document labels on the 9 | #' y-axis) with optional renaming and sorting, or as a plot of estimated 10 | #' feature-level parameters (estimated feature positions on the x-axis, and a 11 | #' measure of relative frequency or influence on the y-axis, with feature names 12 | #' replacing plotting points with some being chosen by the user to be 13 | #' highlighted). 14 | #' @param x the fitted or predicted scaling model object to be plotted 15 | #' @param margin `"documents"` to plot estimated document scores (the 16 | #' default) or `"features"` to plot estimated feature scores by a measure 17 | #' of relative frequency 18 | #' @param sort if `TRUE` (the default), order points from low to high 19 | #' score. If a vector, order according to these values from low to high. Only 20 | #' applies when `margin = "documents"`. 21 | #' @inheritParams quanteda::groups 22 | #' @param doclabels a vector of names for document; if left NULL (the default), 23 | #' docnames will be used 24 | #' @param highlighted a vector of feature names to draw attention to in a 25 | #' feature plot; only applies if `margin = "features"` 26 | #' @param highlighted_color colour for highlighted terms in `highlighted` 27 | #' @param alpha A number between 0 and 1 (default 0.5) representing the level of 28 | #' alpha transparency used to overplot feature names in a feature plot; only 29 | #' applies if `margin = "features"` 30 | #' @return a \pkg{ggplot2} object 31 | #' @note The `groups` argument only applies when `margin = "documents"`. 32 | #' @export 33 | #' @author Kenneth Benoit, Stefan Müller, and Adam Obeng 34 | #' @seealso [quanteda.textmodels::textmodel_wordfish()], 35 | #' [quanteda.textmodels::textmodel_wordscores()], 36 | #' [quanteda.textmodels::textmodel_ca()] 37 | #' @keywords textplot 38 | #' @importMethodsFrom Matrix colSums rowSums t 39 | #' @examples 40 | #' library("quanteda") 41 | #' if (require("quanteda.textmodels")) { 42 | #' dfmat <- dfm(tokens(data_corpus_irishbudget2010)) 43 | #' 44 | #' ## wordscores 45 | #' refscores <- c(rep(NA, 4), 1, -1, rep(NA, 8)) 46 | #' tmod1 <- textmodel_wordscores(dfmat, y = refscores, smooth = 1) 47 | #' # plot estimated document positions 48 | #' textplot_scale1d(predict(tmod1, se.fit = TRUE), 49 | #' groups = data_corpus_irishbudget2010$party) 50 | #' # plot estimated word positions 51 | #' textplot_scale1d(tmod1, margin = "features", 52 | #' highlighted = c("minister", "have", "our", "budget")) 53 | #' 54 | #' ## wordfish 55 | #' tmod2 <- quanteda.textmodels::textmodel_wordfish(dfmat, dir = c(6,5)) 56 | #' # plot estimated document positions 57 | #' textplot_scale1d(tmod2) 58 | #' textplot_scale1d(tmod2, groups = data_corpus_irishbudget2010$party) 59 | #' # plot estimated word positions 60 | #' textplot_scale1d(tmod2, margin = "features", 61 | #' highlighted = c("government", "global", "children", 62 | #' "bank", "economy", "the", "citizenship", 63 | #' "productivity", "deficit")) 64 | #' 65 | #' ## correspondence analysis 66 | #' tmod3 <- textmodel_ca(dfmat) 67 | #' # plot estimated document positions 68 | #' textplot_scale1d(tmod3, margin = "documents", 69 | #' groups = docvars(data_corpus_irishbudget2010, "party")) 70 | #' } 71 | textplot_scale1d <- function(x, 72 | margin = c("documents", "features"), 73 | doclabels = NULL, 74 | sort = TRUE, groups = NULL, 75 | highlighted = NULL, alpha = 0.7, 76 | highlighted_color = "black") { 77 | UseMethod("textplot_scale1d") 78 | } 79 | 80 | #' @export 81 | textplot_scale1d.default <- function(x, 82 | margin = c("documents", "features"), 83 | doclabels = NULL, 84 | sort = TRUE, groups = NULL, 85 | highlighted = NULL, alpha = 0.7, 86 | highlighted_color = "black") { 87 | stop(friendly_class_undefined_message(class(x), "textplot_scale1d")) 88 | } 89 | 90 | #' @importFrom stats reorder aggregate 91 | #' @importFrom ggplot2 ggplot aes geom_point element_blank geom_pointrange 92 | #' @importFrom ggplot2 coord_flip xlab ylab theme_bw geom_text theme geom_point 93 | #' @importFrom ggplot2 facet_grid element_line 94 | #' @export 95 | textplot_scale1d.textmodel_wordfish <- function(x, 96 | margin = c("documents", "features"), 97 | doclabels = NULL, 98 | sort = TRUE, 99 | groups = NULL, 100 | highlighted = NULL, 101 | alpha = 0.7, 102 | highlighted_color = "black") { 103 | margin <- match.arg(margin) 104 | if (is.null(doclabels)) doclabels <- x$docs 105 | 106 | if (margin == "documents") { 107 | p <- textplot_scale1d_documents(x$theta, 108 | x$se.theta, 109 | doclabels = doclabels, 110 | sort = sort, 111 | groups = groups) + 112 | ylab("Estimated theta") 113 | } else if (margin == "features") { 114 | p <- textplot_scale1d_features(x$beta, 115 | weight = x$psi, 116 | featlabels = x$features, 117 | highlighted = highlighted, alpha = alpha, 118 | highlighted_color = highlighted_color) + 119 | xlab("Estimated beta") + 120 | ylab("Estimated psi") 121 | } 122 | apply_theme(p) 123 | } 124 | 125 | #' @importFrom stats reorder aggregate 126 | #' @importFrom ggplot2 ggplot aes geom_point element_blank geom_pointrange 127 | #' @importFrom ggplot2 coord_flip xlab ylab theme_bw geom_text theme geom_point 128 | #' @importFrom ggplot2 facet_grid element_line 129 | #' @method textplot_scale1d predict.textmodel_wordscores 130 | #' @export 131 | textplot_scale1d.predict.textmodel_wordscores <- function(x, 132 | margin = c("documents", "features"), 133 | doclabels = NULL, 134 | sort = TRUE, 135 | groups = NULL, 136 | highlighted = NULL, 137 | alpha = 0.7, 138 | highlighted_color = "black") { 139 | margin <- match.arg(margin) 140 | if (is.null(doclabels)) doclabels <- get_docname(x) 141 | 142 | 143 | if (margin == "documents") { 144 | p <- textplot_scale1d_documents(get_fitted(x), 145 | get_sefit(x), 146 | doclabels = doclabels, 147 | sort = sort, 148 | groups = groups) + 149 | ylab("Document position") 150 | 151 | } else if (margin == "features") { 152 | stop("This margin can only be run on a fitted wordscores object.") 153 | } 154 | apply_theme(p) 155 | } 156 | 157 | 158 | #' @export 159 | textplot_scale1d.textmodel_wordscores <- function(x, 160 | margin = c("features", "documents"), 161 | doclabels = NULL, 162 | sort = TRUE, 163 | groups = NULL, 164 | highlighted = NULL, 165 | alpha = 0.7, 166 | highlighted_color = "black") { 167 | margin <- match.arg(margin) 168 | if (margin == "documents") { 169 | stop("This margin can only be run on a predicted wordscores object.") 170 | } else if (margin == "features") { 171 | p <- textplot_scale1d_features(x$wordscores, 172 | weight = log(colSums(x$x[, names(x$wordscores)])), 173 | featlabels = names(x$wordscores), 174 | highlighted = highlighted, alpha = alpha, 175 | highlighted_color = highlighted_color) + 176 | xlab("Word score") + 177 | ylab("log(term frequency)") 178 | apply_theme(p) 179 | } 180 | } 181 | 182 | #' @importFrom stats reorder aggregate 183 | #' @importFrom ggplot2 ggplot aes geom_point element_blank geom_pointrange 184 | #' @importFrom ggplot2 coord_flip xlab ylab theme_bw geom_text theme geom_point 185 | #' @importFrom ggplot2 facet_grid element_line 186 | #' @importFrom stats coef 187 | #' @export 188 | textplot_scale1d.textmodel_ca <- function(x, 189 | margin = c("documents", "features"), 190 | doclabels = NULL, 191 | sort = TRUE, 192 | groups = NULL, 193 | highlighted = NULL, 194 | alpha = 0.7, 195 | highlighted_color = "black") { 196 | margin <- match.arg(margin) 197 | if (is.null(doclabels)) doclabels <- x$rownames 198 | 199 | if (margin == "documents") { 200 | p <- textplot_scale1d_documents(coef(x)$coef_document, 201 | coef(x)$coef_document_se, 202 | doclabels = doclabels, 203 | sort = sort, 204 | groups = groups) + 205 | ylab("Document position") 206 | 207 | } else { 208 | stop("textplot_scale1d for features not implemented for CA models") 209 | } 210 | apply_theme(p) 211 | } 212 | 213 | 214 | # internal functions ------------------------ 215 | 216 | textplot_scale1d_documents <- function(x, se, doclabels, sort = TRUE, 217 | groups = NULL) { 218 | 219 | if (!is.null(doclabels)) 220 | stopifnot(length(doclabels) == length(x)) 221 | 222 | if (all(is.na(se))) se <- 0 223 | 224 | if (sort & !is.null(groups)) { 225 | temp_medians <- aggregate(x, list(groups), stats::median, na.rm = TRUE) 226 | groups <- factor(groups, 227 | levels = temp_medians[order(temp_medians$x, decreasing = TRUE), 1]) 228 | } 229 | 230 | theta <- lower <- upper <- NULL 231 | results <- data.frame(doclabels = doclabels, 232 | theta = x, 233 | lower = x - 1.96 * se, 234 | upper = x + 1.96 * se) 235 | if (!is.null(groups)) 236 | results$groups <- groups 237 | 238 | p <- if (sort) { 239 | ggplot(data = results, aes(x = reorder(doclabels, theta), y = theta)) 240 | } else { 241 | ggplot(data = results, aes(x = doclabels, y = theta)) 242 | } 243 | 244 | p <- p + 245 | coord_flip() + 246 | geom_point(size = 1) + 247 | geom_pointrange(aes(ymin = lower, ymax = upper), 248 | lwd = .25, fatten = .4) + 249 | xlab(NULL) 250 | if (!is.null(groups)) { 251 | p <- p + facet_grid(as.factor(groups) ~ ., scales = "free_y", space = "free") 252 | } 253 | p 254 | } 255 | 256 | ## 257 | ## internal function to plot document scaling 258 | ## 259 | textplot_scale1d_features <- function(x, weight, featlabels, 260 | highlighted = NULL, alpha = 0.7, 261 | highlighted_color = "black") { 262 | 263 | beta <- psi <- feature <- NULL 264 | results <- data.frame(feature = featlabels, 265 | psi = weight, 266 | beta = x) 267 | p <- ggplot(data = results, aes(x = beta, y = psi, label = feature)) + 268 | geom_text(colour = "grey70", alpha = alpha) + 269 | geom_text(aes(beta, psi, label = feature), 270 | data = results[results$feature %in% highlighted, ], 271 | color = highlighted_color) + 272 | xlab("Beta") + 273 | ylab("Psi") + 274 | theme(panel.grid.major = element_blank(), 275 | panel.grid.minor = element_blank()) 276 | p 277 | } 278 | 279 | ## 280 | ## common minimal B&W theme 281 | ## 282 | apply_theme <- function(p) { 283 | p + theme_bw() + 284 | theme(panel.background = ggplot2::element_blank(), 285 | panel.grid.major.x = element_blank(), 286 | panel.grid.minor.x = element_blank(), 287 | # panel.grid.major.y = element_blank(), 288 | panel.grid.minor.y = element_blank(), 289 | plot.background = element_blank(), 290 | axis.ticks.y = element_blank(), 291 | # panel.spacing = grid::unit(0.1, "lines"), 292 | panel.grid.major.y = element_line(linetype = "dotted")) 293 | } 294 | 295 | get_docname <- function(x) { 296 | if (is.list(x)) { 297 | if (is.matrix(x$fit)) { 298 | return(rownames(x$fit)) 299 | } else { 300 | return(names(x$fit)) 301 | } 302 | } else { 303 | return(names(x)) 304 | } 305 | } 306 | 307 | get_fitted <- function(x) { 308 | if (is.list(x)) { 309 | if (is.matrix(x$fit)) { 310 | return(x$fit[, "fit", drop = TRUE]) 311 | } else { 312 | return(x$fit) 313 | } 314 | } else { 315 | return(x) 316 | } 317 | } 318 | 319 | get_sefit <- function(x) { 320 | if (is.list(x)) { 321 | if (is.matrix(x$fit)) { 322 | return((x$fit[, "fit", drop = TRUE] - x$fit[, "lwr", drop = TRUE]) / 1.96) 323 | } else { 324 | return(x$se.fit) 325 | } 326 | } else { 327 | return(rep(0, length(x))) 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /R/textplot_wordcloud.R: -------------------------------------------------------------------------------- 1 | #' Plot features as a wordcloud 2 | #' 3 | #' Plot a [dfm][quanteda::dfm] or [quanteda.textstats::textstat_keyness] object 4 | #' as a wordcloud, where the feature labels are plotted with their sizes 5 | #' proportional to their numerical values in the dfm. When `comparison = TRUE`, 6 | #' it plots comparison word clouds by document (or by target and reference 7 | #' categories in the case of a keyness object). 8 | #' @details 9 | #' The default is to plot the word cloud of all features, summed across 10 | #' documents. To produce word cloud plots for specific document or set of 11 | #' documents, you need to slice out the document(s) from the dfm object. 12 | #' 13 | #' Comparison wordcloud plots may be plotted by setting `comparison = TRUE`, 14 | #' which plots a separate grouping for *each document* in the dfm. This means 15 | #' that you will need to slice out just a few documents from the dfm, or to 16 | #' create a dfm where the "documents" represent a subset or a grouping of 17 | #' documents by some document variable. 18 | #' 19 | #' @param x a [dfm][quanteda::dfm] or [quanteda.textstats::textstat_keyness] 20 | #' object 21 | #' @param min_size size of the smallest word 22 | #' @param max_size size of the largest word 23 | #' @param min_count words with frequency below min_count will not be plotted 24 | #' @param max_words maximum number of words to be plotted. The least frequent 25 | #' terms dropped. The maximum frequency will be split evenly across 26 | #' categories when `comparison = TRUE`. 27 | #' @param color colour of words from least to most frequent 28 | #' @param font font-family of words and labels. Use default font if `NULL`. 29 | #' @param adjust adjust sizes of words by a constant. Useful for non-English 30 | #' words for which R fails to obtain correct sizes. 31 | #' @param rotation proportion of words with 90 degree rotation 32 | #' @param random_order plot words in random order. If `FALSE`, they will be 33 | #' plotted in decreasing frequency. 34 | #' @param random_color choose colours randomly from the colours. If `FALSE`, 35 | #' the colour is chosen based on the frequency 36 | #' @param ordered_color if `TRUE`, then colours are assigned to words in 37 | #' order. 38 | #' @param labelcolor colour of group labels. Only used when `comparison = TRUE`. 39 | #' @param labelsize size of group labels. Only used when `comparison = TRUE`. 40 | #' @param labeloffset position of group labels. Only used when 41 | #' `comparison = TRUE`. 42 | #' @param fixed_aspect logical; if `TRUE`, the aspect ratio is fixed. Variable 43 | #' aspect ratio only supported if rotation = 0. 44 | #' @param comparison logical; if `TRUE`, plot a wordcloud that compares 45 | #' documents in the same way as [wordcloud::comparison.cloud()]. If `x` is a 46 | #' [quanteda.textstats::textstat_keyness] object, then only the target 47 | #' category's key terms are plotted when `comparison = FALSE`, otherwise the 48 | #' top `max_words / 2` terms are plotted from the target and reference 49 | #' categories. 50 | #' @param ... additional parameters. Only used to make it compatible with 51 | #' \pkg{wordcloud} 52 | #' @export 53 | #' @keywords textplot 54 | #' @author Kohei Watanabe, building on code from Ian Fellows's \pkg{wordcloud} 55 | #' package. 56 | #' @import ggplot2 57 | #' @examples 58 | #' # plot the features (without stopwords) from Obama's inaugural addresses 59 | #' set.seed(10) 60 | #' library("quanteda") 61 | #' dfmat1 <- data_corpus_inaugural |> 62 | #' corpus_subset(President == "Obama") |> 63 | #' tokens(remove_punct = TRUE) |> 64 | #' tokens_remove(stopwords("en")) |> 65 | #' dfm() |> 66 | #' dfm_trim(min_termfreq = 3) 67 | #' 68 | #' # basic wordcloud 69 | #' textplot_wordcloud(dfmat1) 70 | #' 71 | #' # plot in colours with some additional options 72 | #' textplot_wordcloud(dfmat1, rotation = 0.25, 73 | #' color = rev(RColorBrewer::brewer.pal(10, "RdBu"))) 74 | #' 75 | #' # other display options 76 | #' col <- sapply(seq(0.1, 1, 0.1), function(x) adjustcolor("#1F78B4", x)) 77 | #' textplot_wordcloud(dfmat1, adjust = 0.5, random_order = FALSE, 78 | #' color = col, rotation = FALSE) 79 | #' 80 | #' # comparison plot of Obama v. Trump 81 | #' dfmat2 <- data_corpus_inaugural |> 82 | #' corpus_subset(President %in% c("Obama", "Trump")) |> 83 | #' tokens(remove_punct = TRUE) |> 84 | #' tokens_remove(stopwords("en")) |> 85 | #' dfm() 86 | #' dfmat2 <- dfm_group(dfmat2, dfmat2$President) |> 87 | #' dfm_trim(min_termfreq = 3) 88 | #' 89 | #' textplot_wordcloud(dfmat2, comparison = TRUE, max_words = 100, 90 | #' color = c("blue", "red")) 91 | #' 92 | #' \dontrun{ 93 | #' # for keyness 94 | #' tstat <- data_corpus_inaugural[c(1, 3)] |> 95 | #' tokens(remove_punct = TRUE) |> 96 | #' tokens_remove(stopwords("en")) |> 97 | #' dfm() |> 98 | #' quanteda.textstats::textstat_keyness() 99 | #' textplot_wordcloud(tstat, min_count = 2) 100 | #' textplot_wordcloud(tstat, min_count = 2, comparison = FALSE) 101 | #' } 102 | textplot_wordcloud <- function(x, 103 | min_size = 0.5, 104 | max_size = 4, 105 | min_count = 3, 106 | max_words = 500, 107 | color = "darkblue", 108 | font = NULL, 109 | adjust = 0, 110 | rotation = 0.1, 111 | random_order = FALSE, 112 | random_color = FALSE, 113 | ordered_color = FALSE, 114 | labelcolor = "gray20", 115 | labelsize = 1.5, 116 | labeloffset = 0, 117 | fixed_aspect = TRUE, 118 | ..., 119 | comparison = FALSE) { 120 | UseMethod("textplot_wordcloud") 121 | } 122 | 123 | #' @export 124 | textplot_wordcloud.default <- function(x, ..., comparison = FALSE) { 125 | stop(friendly_class_undefined_message(class(x), "textplot_wordcloud")) 126 | } 127 | 128 | #' @export 129 | #' @importFrom quanteda as.dfm ndoc 130 | textplot_wordcloud.dfm <- function(x, 131 | min_size = 0.5, 132 | max_size = 4, 133 | min_count = 3, 134 | max_words = 500, 135 | color = "darkblue", 136 | font = NULL, 137 | adjust = 0, 138 | rotation = 0.1, 139 | random_order = FALSE, 140 | random_color = FALSE, 141 | ordered_color = FALSE, 142 | labelcolor = "gray30", 143 | labelsize = 1.5, 144 | labeloffset = 0.05, 145 | fixed_aspect = TRUE, 146 | ..., 147 | comparison = FALSE) { 148 | 149 | x <- as.dfm(x) 150 | if (!sum(x)) stop(message_error("dfm_empty")) 151 | if (comparison) { 152 | if (ndoc(x) > 8) 153 | stop("Too many documents to plot comparison, use 8 or fewer documents.") 154 | wordcloud_comparison(x, min_size, max_size, min_count, max_words, 155 | color, font, adjust, rotation, 156 | random_order, random_color, ordered_color, 157 | labelcolor, labelsize, labeloffset, fixed_aspect, ...) 158 | } else { 159 | wordcloud(x, min_size, max_size, min_count, max_words, 160 | color, font, adjust, rotation, 161 | random_order, random_color, ordered_color, 162 | labelcolor, labelsize, labeloffset, fixed_aspect, ...) 163 | } 164 | } 165 | 166 | #' @export 167 | #' @importFrom quanteda as.dfm dfm_trim 168 | textplot_wordcloud.keyness <- function(x, ..., max_words = 100, 169 | comparison = TRUE) { 170 | n <- if (!comparison) max_words else floor(max_words / 2) 171 | # transform into a dfm 172 | mat <- as.matrix(x[, c("n_target", "n_reference")]) 173 | dimnames(mat) <- list(x$feature, attr(x, "groups")) 174 | mat <- utils::head(mat, n) 175 | if (comparison) mat <- rbind(utils::tail(mat, n)) 176 | mat <- as.dfm(t(mat)) 177 | 178 | # slice out the target only if comparison is not wanted 179 | if (!comparison) { 180 | mat <- dfm_trim(mat[1, ], min_termfreq = 1) 181 | } 182 | 183 | textplot_wordcloud(mat, ..., max_words = max_words, comparison = comparison) 184 | } 185 | 186 | # internal ---------- 187 | 188 | #' Internal function for textplot_wordcloud 189 | #' 190 | #' This function implements wordcloud without dependencies. Code is adopted from 191 | #' [wordcloud::wordcloud()]. 192 | #' @inheritParams textplot_wordcloud 193 | #' @param scale deprecated argument 194 | #' @param min.freq deprecated argument 195 | #' @param max.words deprecated argument 196 | #' @param random.order deprecated argument 197 | #' @param random.color deprecated argument 198 | #' @param rot.per deprecated argument 199 | #' @param ordered.colors deprecated argument 200 | #' @param use.r.layout deprecated argument 201 | #' @param fixed.asp deprecated argument 202 | #' @importFrom graphics text 203 | #' @importFrom quanteda dfm_trim 204 | #' @keywords internal 205 | #' @author Kohei Watanabe, building on code from Ian Fellows's \pkg{wordcloud} package. 206 | wordcloud <- function(x, min_size, max_size, min_count, max_words, 207 | color, font, adjust, rotation, 208 | random_order, random_color, ordered_color, 209 | labelcolor, labelsize, labeloffset, fixed_aspect, 210 | # deprecated arguments 211 | colors, scale, min.freq, max.words, random.order, 212 | random.color, rot.per, ordered.colors, use.r.layout, fixed.asp, ...) { 213 | 214 | arg_dep <- character() 215 | if (!missing(min.freq)) { 216 | min_count <- min.freq 217 | arg_dep <- c(arg_dep, "min_count" = "min.freq") 218 | } 219 | if (!missing(colors)) { 220 | color <- colors 221 | arg_dep <- c(arg_dep, "color" = "colors") 222 | } 223 | if (!missing(scale)) { 224 | max_size <- scale[1] 225 | min_size <- scale[2] 226 | arg_dep <- c(arg_dep, "min_size and max_size" = "scale") 227 | } 228 | if (!missing(max.words)) { 229 | max_words <- max.words 230 | arg_dep <- c(arg_dep, "max_words" = "max.words") 231 | } 232 | if (!missing(random.order)) { 233 | random_order <- random.order 234 | arg_dep <- c(arg_dep, "random_order" = "random.order") 235 | } 236 | if (!missing(random.color)) { 237 | random_color <- random.color 238 | arg_dep <- c(arg_dep, "random_color" = "random.color") 239 | } 240 | if (!missing(rot.per)) { 241 | rotation <- rot.per 242 | arg_dep <- c(arg_dep, "rotation" = "rot.per") 243 | } 244 | if (!missing(ordered.colors)) { 245 | ordered_color <- ordered.colors 246 | arg_dep <- c(arg_dep, "ordered_color" = "ordered.colors") 247 | } 248 | if (!missing(use.r.layout)) { 249 | warning("use.r.layout is no longer used", call. = FALSE) 250 | } 251 | if (!missing(fixed.asp)) { 252 | fixed_aspect <- fixed.asp 253 | arg_dep <- c(arg_dep, "fixed_aspect" = "fixed.asp") 254 | } 255 | if (length(arg_dep)) 256 | warning(paste(arg_dep), " is deprecated; use ", paste(names(arg_dep)), " instead", call. = FALSE) 257 | 258 | if (!fixed_aspect && rotation > 0) 259 | stop("Variable aspect ratio not supported for rotated words. Set rotation=0.") 260 | 261 | tails <- "g|j|p|q|y" 262 | nc <- length(color) 263 | 264 | font <- check_font(font) 265 | x <- dfm_trim(x, min_termfreq = min_count) 266 | # check to see that dfm is not empty 267 | if (!sum(x)) stop("No features left after trimming with min_count = ", min_count) 268 | freq <- Matrix::colSums(x) 269 | word <- names(freq) 270 | freq <- unname(freq) 271 | 272 | if (ordered_color) { 273 | if (length(color) != 1 && length(color) != length(word)) { 274 | stop("Length of color does not match length of word vector") 275 | } 276 | } 277 | 278 | ord <- rank(-freq, ties.method = "random") 279 | word <- word[ord <= max_words] 280 | freq <- freq[ord <= max_words] 281 | if (ordered_color) { 282 | color <- color[ord <= max_words] 283 | } 284 | 285 | if (random_order) { 286 | ord <- sample.int(length(word)) 287 | } else { 288 | ord <- order(freq, decreasing = TRUE) 289 | } 290 | word <- word[ord] 291 | freq <- freq[ord] 292 | 293 | theta_step <- 0.1 294 | r_step <- 0.05 295 | 296 | op <- graphics::par(no.readonly = TRUE) 297 | on.exit(graphics::par(op)) 298 | graphics::par(mar = c(0, 0, 0, 0), usr = c(-1, 1, -1, 1), family = font) 299 | graphics::plot.new() 300 | 301 | if (fixed_aspect) { 302 | graphics::plot.window(c(0, 1), c(0, 1), asp = 1) 303 | } else { 304 | graphics::plot.window(c(0, 1), c(0, 1)) 305 | } 306 | freq <- freq / max(freq) 307 | size <- (max_size - min_size) * freq + min_size 308 | size <- size * (min(grDevices::dev.size("in")) / 7) # default window size is 7 in 309 | boxes <- list() 310 | for (i in seq_along(word)) { 311 | rot <- stats::runif(1) < rotation 312 | r <- 0 313 | theta <- stats::runif(1, 0, 2 * pi) 314 | x1 <- 0.5 315 | y1 <- 0.5 316 | 317 | wd <- graphics::strwidth(word[i], cex = size[i]) 318 | ht <- graphics::strheight(word[i], cex = size[i]) 319 | 320 | if (grepl(tails, word[i])) 321 | ht <- ht * 1.2 # extra height for g, j, p, q, y 322 | if (rot) { 323 | tp <- ht 324 | ht <- wd 325 | wd <- tp 326 | } 327 | 328 | is_overlapped <- TRUE 329 | while (is_overlapped) { 330 | if (!qatd_cpp_is_overlap(x1 - 0.5 * wd, y1 - 0.5 * ht, wd, ht, boxes) && 331 | x1 - 0.5 * wd > 0 && y1 - 0.5 * ht > 0 && 332 | x1 + 0.5 * wd < 1 && y1 + 0.5 * ht < 1) { 333 | if (!random_color) { 334 | if (ordered_color) { 335 | cc <- color[i] 336 | } else { 337 | cc <- ceiling(nc * freq[i]) 338 | cc <- color[cc] 339 | } 340 | } else { 341 | cc <- color[sample(seq(nc), 1)] 342 | } 343 | text(x1, y1, word[i], cex = (1 + adjust) * size[i], offset = 0, srt = rot * 90, col = cc, ...) 344 | boxes[[length(boxes) + 1]] <- c(x1 - 0.5 * wd, y1 - 0.5 * ht, wd, ht) 345 | is_overlapped <- FALSE 346 | } else { 347 | if (r > sqrt(0.5)) { 348 | warning(paste(word[i], "could not be fit on page. It will not be plotted.")) 349 | is_overlapped <- FALSE 350 | } 351 | theta <- theta + theta_step 352 | r <- r + r_step * theta_step / (2 * pi) 353 | x1 <- 0.5 + r * cos(theta) 354 | y1 <- 0.5 + r * sin(theta) 355 | } 356 | } 357 | } 358 | #abline(v=c(0, 0.25, 0.75, 1), h=c(0, 0.25, 0.75, 1)) 359 | graphics::par(op) 360 | } 361 | 362 | #' Internal function for textplot_wordcloud 363 | #' 364 | #' This function implements wordcloud that compares documents. Code is adopted 365 | #' from [wordcloud::comparison.cloud()]. 366 | #' @inheritParams textplot_wordcloud 367 | #' @param scale deprecated argument 368 | #' @param min.freq deprecated argument 369 | #' @param max.words deprecated argument 370 | #' @param random.order deprecated argument 371 | #' @param rot.per deprecated argument 372 | #' @param use.r.layout deprecated argument 373 | #' @param title.size deprecated argument 374 | #' @importFrom quanteda dfm_trim dfm_weight 375 | #' @importMethodsFrom quanteda t 376 | #' @keywords internal 377 | #' @keywords textplot_internal 378 | #' @author Kohei Watanabe, build on code from Ian Fellows's \pkg{wordcloud} package. 379 | wordcloud_comparison <- function(x, min_size, max_size, min_count, max_words, 380 | color, font, adjust, rotation, 381 | random_order, random_color, ordered_color, 382 | labelcolor, labelsize, labeloffset, fixed_aspect, 383 | # deprecated arguments 384 | colors, scale, min.freq, max.words, 385 | random.order, rot.per, use.r.layout, title.size, ...) { 386 | 387 | arg_dep <- character() 388 | if (!missing(min.freq)) { 389 | min_count <- min.freq 390 | arg_dep <- c(arg_dep, "min_count" = "min.freq") 391 | } 392 | if (!missing(colors)) { 393 | color <- colors 394 | arg_dep <- c(arg_dep, "color" = "colors") 395 | } 396 | if (!missing(scale)) { 397 | max_size <- scale[1] 398 | min_size <- scale[2] 399 | arg_dep <- c(arg_dep, "min_size and max_size" = "scale") 400 | } 401 | if (!missing(max.words)) { 402 | max_words <- max.words 403 | arg_dep <- c(arg_dep, "max_words" = "max.words") 404 | } 405 | if (!missing(random.order)) { 406 | random_order <- random.order 407 | arg_dep <- c(arg_dep, "random_order" = "random.order") 408 | } 409 | if (!missing(rot.per)) { 410 | rotation <- rot.per 411 | arg_dep <- c(arg_dep, "rotation" = "rot.per") 412 | } 413 | if (!missing(use.r.layout)) { 414 | warning("use.r.layout is no longer used", call. = FALSE) 415 | } 416 | if (!missing(title.size)) { 417 | labelsize <- title.size 418 | arg_dep <- c(arg_dep, "labelsize" = "title.size") 419 | } 420 | if (length(arg_dep)) { 421 | warning(paste(arg_dep), " is deprecated; use ", paste(names(arg_dep)), " instead", call. = FALSE) 422 | } 423 | 424 | font <- check_font(font) 425 | x <- dfm_trim(x, min_termfreq = min_count) 426 | x <- dfm_weight(x, "prop") 427 | x <- t(x) - Matrix::colMeans(x) 428 | x <- as.matrix(x) 429 | 430 | ndoc <- ncol(x) 431 | theta_bins <- seq(0, 2 * pi, length = ndoc + 1) 432 | 433 | if (length(color) < ndoc) 434 | color <- RColorBrewer::brewer.pal(8, "Paired") 435 | group <- apply(x, 1, which.max) 436 | word <- rownames(x) 437 | freq <- apply(x, 1, max) 438 | 439 | tails <- "g|j|p|q|y" 440 | # nc <- length(color) 441 | 442 | ord <- rank(-freq, ties.method = "random") 443 | word <- word[ord <= max_words] 444 | freq <- freq[ord <= max_words] 445 | group <- group[ord <= max_words] 446 | 447 | if (random_order) { 448 | ord <- sample.int(length(word)) 449 | } else { 450 | ord <- order(freq, decreasing = TRUE) 451 | } 452 | word <- word[ord] 453 | freq <- freq[ord] 454 | group <- group[ord] 455 | theta_step <- 0.05 456 | r_step <- 0.05 457 | 458 | op <- graphics::par(no.readonly = TRUE) 459 | on.exit(graphics::par(op)) 460 | graphics::par(mar = c(0, 0, 0, 0), usr = c(-1, 1, -1, 1), family = font) 461 | graphics::plot.new() 462 | if (labelsize > 0) { 463 | graphics::plot.window(c(-0.1, 1.1), c(-0.1, 1.1), asp = 1) 464 | } else { 465 | graphics::plot.window(c(0, 1), c(0, 1), asp = 1) 466 | } 467 | freq <- freq / max(freq) 468 | size <- (max_size - min_size) * freq + min_size 469 | size <- size * (min(grDevices::dev.size("in")) / 7) # default window size is 7 in 470 | boxes <- list() 471 | 472 | docnames <- colnames(x) 473 | for (i in seq(ncol(x))) { 474 | theta <- mean(theta_bins[seq(i, i + 1)]) 475 | label <- docnames[i] 476 | if (labelsize > 0) { 477 | wd <- graphics::strwidth(label, cex = labelsize) 478 | ht <- graphics::strheight(label, cex = labelsize) 479 | 480 | x1 <- 0.5 + (0.5 + (labeloffset / 0.5)) * cos(theta) 481 | y1 <- 0.5 + (0.5 + (labeloffset / 0.5)) * sin(theta) 482 | text(x1, y1, label, cex = labelsize, offset = 0, col = labelcolor) 483 | boxes[[length(boxes) + 1]] <- c(x1 - 0.5 * wd, y1 - 0.5 * ht, wd, ht) 484 | } 485 | } 486 | 487 | for (i in seq_along(word)) { 488 | rot <- stats::runif(1) < rotation 489 | r <- 0 490 | theta <- stats::runif(1, 0, 2 * pi) 491 | x1 <- 0.5 492 | y1 <- 0.5 493 | wd <- graphics::strwidth(word[i], cex = size[i]) 494 | ht <- graphics::strheight(word[i], cex = size[i]) 495 | 496 | if (grepl(tails, word[i])) 497 | ht <- ht * 1.2 # extra height for g, j, p, q, y 498 | if (rot) { 499 | tm <- ht 500 | ht <- wd 501 | wd <- tm 502 | } 503 | is_overlapped <- TRUE 504 | while (is_overlapped) { 505 | in_correct_region <- theta > theta_bins[group[i]] && theta < theta_bins[group[i] + 1] 506 | if (in_correct_region && !qatd_cpp_is_overlap( 507 | x1 - 0.5 * wd, y1 - 0.5 * ht, wd, ht, boxes) && 508 | x1 - 0.5 * wd > 0 && y1 - 0.5 * ht > 0 && 509 | x1 + 0.5 * wd < 1 && y1 + 0.5 * ht < 1) { 510 | 511 | text(x1, y1, word[i], cex = (1 + adjust) * size[i], 512 | offset = 0, srt = rot * 90, col = color[group[i]], ...) 513 | boxes[[length(boxes) + 1]] <- c(x1 - 0.5 * wd, y1 - 0.5 * ht, wd, ht) 514 | is_overlapped <- FALSE 515 | 516 | } else { 517 | if (r > sqrt(0.5)) { 518 | warning(paste(word[i], "could not be fit on page. It will not be plotted.")) 519 | is_overlapped <- FALSE 520 | } 521 | theta <- theta + theta_step 522 | if (theta > 2 * pi) 523 | theta <- theta - 2 * pi 524 | r <- r + r_step * theta_step / (2 * pi) 525 | x1 <- 0.5 + r * cos(theta) 526 | y1 <- 0.5 + r * sin(theta) 527 | } 528 | } 529 | } 530 | #abline(v=c(0, 0.25, 0.75, 1), h=c(0, 0.25, 0.75, 1)) 531 | graphics::par(op) 532 | } 533 | -------------------------------------------------------------------------------- /tests/data/stjohn_latin.csv: -------------------------------------------------------------------------------- 1 | chapter,verse,english,latin 2 | 1,1,In the beginning was the Word: and the Word was with God: and the Word was God.,in principio erat Verbum et Verbum erat apud Deum et Deus erat Verbum 3 | 1,2,The same was in the beginning with God.,hoc erat in principio apud Deum 4 | 1,3,All things were made by him: and without him was made nothing that was made.,omnia per ipsum facta sunt et sine ipso factum est nihil quod factum est 5 | 1,4,In him was life: and the life was the light of men.,in ipso vita erat et vita erat lux hominum 6 | 1,5,And the light shineth in darkness: and the darkness did not comprehend it.,et lux in tenebris lucet et tenebrae eam non conprehenderunt 7 | 1,6,"There was a man sent from God, whose name was John.",fuit homo missus a Deo cui nomen erat Iohannes 8 | 1,7,"This man came for a witness, to give testimony of the light, that all men might believe through him.",hic venit in testimonium ut testimonium perhiberet de lumine ut omnes crederent per illum 9 | 1,8,"He was not the light, but was to give testimony of the light.",non erat ille lux sed ut testimonium perhiberet de lumine 10 | 1,9,"That was the true light, which enlighteneth every man that cometh into this world.",erat lux vera quae inluminat omnem hominem venientem in mundum 11 | 1,10,He was in the world: and the world was made by him: and the world knew him not.,in mundo erat et mundus per ipsum factus est et mundus eum non cognovit 12 | 1,11,He came unto his own: and his own received him not.,in propria venit et sui eum non receperunt 13 | 1,12,"But as many as received him, he gave them power to be made the sons of God, to them that believe in his name.",quotquot autem receperunt eum dedit eis potestatem filios Dei fieri his qui credunt in nomine eius 14 | 1,13,"Who are born, not of blood, nor of the will of the flesh, nor of the will of man, but of God.",qui non ex sanguinibus neque ex voluntate carnis neque ex voluntate viri sed ex Deo nati sunt 15 | 1,14,"And the Word was made flesh and dwelt among us (and we saw his glory, the glory as it were of the only begotten of the Father), full of grace and truth.",et Verbum caro factum est et habitavit in nobis et vidimus gloriam eius gloriam quasi unigeniti a Patre plenum gratiae et veritatis 16 | 1,15,"John beareth witness of him and crieth out, saying: This was he of whom I spoke: He that shall come after me is preferred before me: because he was before me.",Iohannes testimonium perhibet de ipso et clamat dicens hic erat quem dixi vobis qui post me venturus est ante me factus est quia prior me erat 17 | 1,16,And of his fulness we all have received: and grace for grace.,et de plenitudine eius nos omnes accepimus et gratiam pro gratia 18 | 1,17,For the law was given by Moses: grace and truth came by Jesus Christ.,quia lex per Mosen data est gratia et veritas per Iesum Christum facta est 19 | 1,18,"No man hath seen God at any time: the only begotten Son who is in the Bosom of the Father, he hath declared him.",Deum nemo vidit umquam unigenitus Filius qui est in sinu Patris ipse enarravit 20 | 1,19,"And this is the testimony of John, when the Jews sent from Jerusalem priests and Levites to him, to ask him: Who art thou?",et hoc est testimonium Iohannis quando miserunt Iudaei ab Hierosolymis sacerdotes et Levitas ad eum ut interrogarent eum tu quis es 21 | 1,20,And he confessed and did not deny: and he confessed: I am not the Christ.,et confessus est et non negavit et confessus est quia non sum ego Christus 22 | 1,21,And they asked him: What then? Art thou Elias? And he said: I am not. Art thou the prophet? And he answered: No.,et interrogaverunt eum quid ergo Helias es tu et dicit non sum propheta es tu et respondit non 23 | 1,22,"They said therefore unto him: Who art thou, that we may give an answer to them that sent us? What sayest thou of thyself?",dixerunt ergo ei quis es ut responsum demus his qui miserunt nos quid dicis de te ipso 24 | 1,23,"He said: I am the voice of one crying in the wilderness, make straight the way of the Lord, as said the prophet Isaias.",ait ego vox clamantis in deserto dirigite viam Domini sicut dixit Esaias propheta 25 | 1,24,And they that were sent were of the Pharisees.,et qui missi fuerant erant ex Pharisaeis 26 | 1,25,"And they asked him and said to him: Why then dost thou baptize, if thou be not Christ, nor Elias, nor the prophet?",et interrogaverunt eum et dixerunt ei quid ergo baptizas si tu non es Christus neque Helias neque propheta 27 | 1,26,"John answered them, saying: I baptize with water: but there hath stood one in the midst of you, whom you know not.",respondit eis Iohannes dicens ego baptizo in aqua medius autem vestrum stetit quem vos non scitis 28 | 1,27,"The same is he that shall come after me, who is preferred before me: the latchet of whose shoe I am not worthy to loose.",ipse est qui post me venturus est qui ante me factus est cuius ego non sum dignus ut solvam eius corrigiam calciamenti 29 | 1,28,"These things were done in Bethania, beyond the Jordan, where John was baptizing.",haec in Bethania facta sunt trans Iordanen ubi erat Iohannes baptizans 30 | 1,29,"The next day, John saw Jesus coming to him; and he saith: Behold the Lamb of God. Behold him who taketh away the sin of the world.",altera die videt Iohannes Iesum venientem ad se et ait ecce agnus Dei qui tollit peccatum mundi 31 | 1,30,"This is he of whom I said: After me there cometh a man, who is preferred before me: because he was before me.",hic est de quo dixi post me venit vir qui ante me factus est quia prior me erat 32 | 1,31,"And I knew him not: but that he may be made manifest in Israel, therefore am I come baptizing with water.",et ego nesciebam eum sed ut manifestaretur Israhel propterea veni ego in aqua baptizans 33 | 1,32,"And John gave testimony, saying: I saw the Spirit coming down, as a dove from heaven; and he remained upon him.",et testimonium perhibuit Iohannes dicens quia vidi Spiritum descendentem quasi columbam de caelo et mansit super eum 34 | 1,33,"And I knew him not: but he who sent me to baptize with water said to me: He upon whom thou shalt see the Spirit descending and remaining upon him, he it is that baptizeth with the Holy Ghost.",et ego nesciebam eum sed qui misit me baptizare in aqua ille mihi dixit super quem videris Spiritum descendentem et manentem super eum hic est qui baptizat in Spiritu Sancto 35 | 1,34,And I saw: and I gave testimony that this is the Son of God.,et ego vidi et testimonium perhibui quia hic est Filius Dei 36 | 1,35,The next day again John stood and two of his disciples.,altera die iterum stabat Iohannes et ex discipulis eius duo 37 | 1,36,"And beholding Jesus walking, he saith: Behold the Lamb of God.",et respiciens Iesum ambulantem dicit ecce agnus Dei 38 | 1,37,And the two disciples heard him speak: and they followed Jesus.,et audierunt eum duo discipuli loquentem et secuti sunt Iesum 39 | 1,38,"And Jesus turning and seeing them following him, saith to them: What seek you? Who said to him: Rabbi (which is to say, being interpreted, Master), where dwellest thou?",conversus autem Iesus et videns eos sequentes dicit eis quid quaeritis qui dixerunt ei rabbi quod dicitur interpretatum magister ubi habitas 40 | 1,39,He saith to them: Come and see. They came and saw where he abode: and they stayed with him that day. Now it was about the tenth hour.,dicit eis venite et videte venerunt et viderunt ubi maneret et apud eum manserunt die illo hora autem erat quasi decima 41 | 1,40,"And Andrew, the brother of Simon Peter, was one of the two who had heard of John and followed him.",erat autem Andreas frater Simonis Petri unus ex duobus qui audierant ab Iohanne et secuti fuerant eum 42 | 1,41,"He findeth first his brother Simon and saith to him: We have found the Messias, which is, being interpreted, the Christ.",invenit hic primum fratrem suum Simonem et dicit ei invenimus Messiam quod est interpretatum Christus 43 | 1,42,"And he brought him to Jesus. And Jesus looking upon him, said: Thou art Simon the son of Jona. Thou shalt be called Cephas, which is interpreted Peter.",et adduxit eum ad Iesum intuitus autem eum Iesus dixit tu es Simon filius Iohanna tu vocaberis Cephas quod interpretatur Petrus 44 | 1,43,"On the following day, he would go forth into Galilee: and he findeth Philip, And Jesus saith to him: follow me.",in crastinum voluit exire in Galilaeam et invenit Philippum et dicit ei Iesus sequere me 45 | 1,44,"Now Philip was of Bethsaida, the city of Andrew and Peter.",erat autem Philippus a Bethsaida civitate Andreae et Petri 46 | 1,45,"Philip findeth Nathanael and saith to him: We have found him of whom Moses, in the law and the prophets did write, Jesus the son of Joseph of Nazareth.",invenit Philippus Nathanahel et dicit ei quem scripsit Moses in lege et prophetae invenimus Iesum filium Ioseph a Nazareth 47 | 1,46,And Nathanael said to him: Can any thing of good come from Nazareth? Philip saith to him: Come and see.,et dixit ei Nathanahel a Nazareth potest aliquid boni esse dicit ei Philippus veni et vide 48 | 1,47,"Jesus saw Nathanael coming to him and he saith of him: Behold an Israelite indeed, in whom there is no guile.",vidit Iesus Nathanahel venientem ad se et dicit de eo ecce vere Israhelita in quo dolus non est 49 | 1,48,"Nathanael saith to him: Whence knowest thou me? Jesus answered and said to him:Before that Philip called thee, when thou wast under the fig tree, I saw thee.",dicit ei Nathanahel unde me nosti respondit Iesus et dixit ei priusquam te Philippus vocaret cum esses sub ficu vidi te 50 | 1,49,Nathanael answered him and said: Rabbi: Thou art the Son of God. Thou art the King of Israel.,respondit ei Nathanahel et ait rabbi tu es Filius Dei tu es rex Israhel 51 | 1,50,"Jesus answered and said to him: Because I said unto thee, I saw thee under the fig tree, thou believest: greater things than these shalt thou see.",respondit Iesus et dixit ei quia dixi tibi vidi te sub ficu credis maius his videbis 52 | 1,51,"And he saith to him: Amen, amen, I say to you, you shall see the heaven opened and the angels of God ascending and descending upon the Son of man.",et dicit ei amen amen dico vobis videbitis caelum apertum et angelos Dei ascendentes et descendentes supra Filium hominis 53 | 2,1,"And the third day, there was a marriage in Cana of Galilee: and the mother of Jesus was there.",et die tertio nuptiae factae sunt in Cana Galilaeae et erat mater Iesu ibi 54 | 2,2,"And Jesus also was invited, and his disciples, to the marriage.",vocatus est autem ibi et Iesus et discipuli eius ad nuptias 55 | 2,3,"And the wine failing, the mother of Jesus saith to him: They have no wine.",et deficiente vino dicit mater Iesu ad eum vinum non habent 56 | 2,4,"And Jesus saith to her: Woman, what is that to me and to thee? My hour is not yet come.",et dicit ei Iesus quid mihi et tibi est mulier nondum venit hora mea 57 | 2,5,"His mother saith to the waiters: Whatsoever he shall say to you, do ye.",dicit mater eius ministris quodcumque dixerit vobis facite 58 | 2,6,"Now there were set there six waterpots of stone, according to the manner of the purifying of the Jews, containing two or three measures apiece.",erant autem ibi lapideae hydriae sex positae secundum purificationem Iudaeorum capientes singulae metretas binas vel ternas 59 | 2,7,Jesus saith to them: Fill the waterpots with water. And they filled them up to the brim.,dicit eis Iesus implete hydrias aquaet impleverunt eas usque ad summum 60 | 2,8,And Jesus saith to them: Draw out now and carry to the chief steward of the feast. And they carried it.,et dicit eis Iesus haurite nunc et ferte architriclino et tulerunt 61 | 2,9,"And when the chief steward had tasted the water made wine and knew not whence it was, but the waiters knew who had drawn the water: the chief steward calleth the bridegroom,",ut autem gustavit architriclinus aquam vinum factam et non sciebat unde esset ministri autem sciebant qui haurierant aquam vocat sponsum architriclinus 62 | 2,10,"And saith to him: Every man at first setteth forth good wine, and when men have well drunk, then that which is worse. But thou hast kept the good wine until now.",et dicit ei omnis homo primum bonum vinum ponit et cum inebriati fuerint tunc id quod deterius est tu servasti bonum vinum usque adhuc 63 | 2,11,This beginning of miracles did Jesus in Cana of Galilee and manifested his glory. And his disciples believed in him.,hoc fecit initium signorum Iesus in Cana Galilaeae et manifestavit gloriam suam et crediderunt in eum discipuli eius 64 | 2,12,"After this, he went down to Capharnaum, he and his mother and his brethren and his disciples: and they remained there not many days.",post hoc descendit Capharnaum ipse et mater eius et fratres eius et discipuli eius et ibi manserunt non multis diebus 65 | 2,13,And the pasch of the Jews was at hand: and Jesus went up to Jerusalem.,et prope erat pascha Iudaeorum et ascendit Hierosolyma Iesus 66 | 2,14,"And he found in the temple them that sold oxen and sheep and doves, and the changers of money sitting.",et invenit in templo vendentes boves et oves et columbas et nummularios sedentes 67 | 2,15,"And when he had made, as it were, a scourge of little cords, he drove them all out of the temple, the sheep also and the oxen: and the money of the changers he poured out, and the tables he overthrew.",et cum fecisset quasi flagellum de funiculis omnes eiecit de templo oves quoque et boves et nummulariorum effudit aes et mensas subvertit 68 | 2,16,"And to them that sold doves he said: Take these things hence, and make not the house of my Father a house of traffic.",et his qui columbas vendebant dixit auferte ista hinc nolite facere domum Patris mei domum negotiationis 69 | 2,17,"And his disciples remembered, that it was written: The zeal of thy house hath eaten me up.",recordati vero sunt discipuli eius quia scriptum est zelus domus tuae comedit me 70 | 2,18,"The Jews, therefore, answered, and said to him: What sign dost thou shew unto us, seeing thou dost these things?",responderunt ergo Iudaei et dixerunt ei quod signum ostendis nobis quia haec facis 71 | 2,19,Jesus answered and said to them: Destroy this temple; and in three days I will raise it up.,respondit Iesus et dixit eis solvite templum hoc et in tribus diebus excitabo illud 72 | 2,20,The Jews then said: Six and forty years was this temple in building; and wilt thou raise it up in three days?,dixerunt ergo Iudaei quadraginta et sex annis aedificatum est templum hoc et tu tribus diebus excitabis illud 73 | 2,21,But he spoke of the temple of his body.,ille autem dicebat de templo corporis sui 74 | 2,22,"When therefore he was risen again from the dead, his disciples remembered that he had said this: and they believed the scripture and the word that Jesus had said.",cum ergo resurrexisset a mortuis recordati sunt discipuli eius quia hoc dicebat et crediderunt scripturae et sermoni quem dixit Iesus 75 | 2,23,"Now when he was at Jerusalem, at the pasch, upon the festival day, many believed in his name, seeing his signs which he did.",cum autem esset Hierosolymis in pascha in die festo multi crediderunt in nomine eius videntes signa eius quae faciebat 76 | 2,24,"But Jesus did not trust himself unto them: for that he knew all men,",ipse autem Iesus non credebat semet ipsum eis eo quod ipse nosset omnes 77 | 2,25,And because he needed not that any should give testimony of man: for he knew what was in man.,et quia opus ei non erat ut quis testimonium perhiberet de homine ipse enim sciebat quid esset in homine 78 | 3,1,"And there was a man of the Pharisees, named Nicodemus, a ruler of the Jews.",erat autem homo ex Pharisaeis Nicodemus nomine princeps Iudaeorum 79 | 3,2,"This man came to Jesus by night and said to him: Rabbi, we know that thou art come a teacher from God; for no man can do these signs which thou dost, unless God be with him.",hic venit ad eum nocte et dixit ei rabbi scimus quia a Deo venisti magister nemo enim potest haec signa facere quae tu facis nisi fuerit Deus cum eo 80 | 3,3,"Jesus answered and said to him: Amen, amen, I say to thee, unless a man be born again, he cannot see the kingdom of God.",respondit Iesus et dixit ei amen amen dico tibi nisi quis natus fuerit denuo non potest videre regnum Dei 81 | 3,4,Nicodemus saith to him: How can a man be born when he is old? Can he enter a second time into his mother's womb and be born again?,dicit ad eum Nicodemus quomodo potest homo nasci cum senex sit numquid potest in ventrem matris suae iterato introire et nasci 82 | 3,5,"Jesus answered: Amen, amen, I say to thee, unless a man be born again of water and the Holy Ghost, he cannot enter into the kingdom of God.",respondit Iesus amen amen dico tibi nisi quis renatus fuerit ex aqua et Spiritu non potest introire in regnum Dei 83 | 3,6,That which is born of the flesh is flesh: and that which is born of the Spirit is spirit.,quod natum est ex carne caro est et quod natum est ex Spiritu spiritus est 84 | 3,7,Wonder not that I said to thee: You must be born again.,non mireris quia dixi tibi oportet vos nasci denuo 85 | 3,8,The Spirit breatheth where he will and thou hearest his voice: but thou knowest not whence he cometh and whither he goeth. So is every one that is born of the Spirit.,Spiritus ubi vult spirat et vocem eius audis sed non scis unde veniat et quo vadat sic est omnis qui natus est ex Spiritu 86 | 3,9,Nicodemus answered and said to him: How can these things be done?,respondit Nicodemus et dixit ei quomodo possunt haec fieri 87 | 3,10,"Jesus answered and said to him: Art thou a master in Israel, and knowest not these things?",respondit Iesus et dixit ei tu es magister Israhel et haec ignoras 88 | 3,11,"Amen, amen, I say to thee that we speak what we know and we testify what we have seen: and you receive not our testimony.",amen amen dico tibi quia quod scimus loquimur et quod vidimus testamur et testimonium nostrum non accipitis 89 | 3,12,"If I have spoken to you earthly things, and you believe not: how will you believe, if I shall speak to you heavenly things?",si terrena dixi vobis et non creditis quomodo si dixero vobis caelestia credetis 90 | 3,13,"And no man hath ascended into heaven, but he that descended from heaven, the Son of man who is in heaven.",et nemo ascendit in caelum nisi qui descendit de caelo Filius hominis qui est in caelo 91 | 3,14,"And as Moses lifted up the serpent in the desert, so must the Son of man be lifted up:",et sicut Moses exaltavit serpentem in deserto ita exaltari oportet Filium hominis 92 | 3,15,"That whosoever believeth in him may not perish, but may have life everlasting.",ut omnis qui credit in ipso non pereat sed habeat vitam aeternam 93 | 3,16,"For God so loved the world, as to give his only begotten Son: that whosoever believeth in him may not perish, but may have life everlasting.",sic enim dilexit Deus mundum ut Filium suum unigenitum daret ut omnis qui credit in eum non pereat sed habeat vitam aeternam 94 | 3,17,"For God sent not his Son into the world, to judge the world: but that the world may be saved by him.",non enim misit Deus Filium suum in mundum ut iudicet mundum sed ut salvetur mundus per ipsum 95 | 3,18,He that believeth in him is not judged. But he that doth not believe is already judged: because he believeth not in the name of the only begotten Son of God.,qui credit in eum non iudicatur qui autem non credit iam iudicatus est quia non credidit in nomine unigeniti Filii Dei 96 | 3,19,And this is the judgment: Because the light is come into the world and men loved darkness rather than the light: for their works were evil.,hoc est autem iudicium quia lux venit in mundum et dilexerunt homines magis tenebras quam lucem erant enim eorum mala opera 97 | 3,20,"For every one that doth evil hateth the light and cometh not to the light, that his works may not be reproved.",omnis enim qui mala agit odit lucem et non venit ad lucem ut non arguantur opera eius 98 | 3,21,"But he that doth truth cometh to the light, that his works may be made manifest: because they are done in God.",qui autem facit veritatem venit ad lucem ut manifestentur eius opera quia in Deo sunt facta 99 | 3,22,"After these things, Jesus and his disciples came into the land of Judea: and there he abode with them and baptized.",post haec venit Iesus et discipuli eius in iudaeam terram et illic demorabatur cum eis et baptizabat 100 | 3,23,And John also was baptizing in Ennon near Salim: because there was much water there. And they came and were baptized.,erat autem et Iohannes baptizans in Aenon iuxta Salim quia aquae multae erant illic et adveniebant et baptizabantur 101 | 3,24,For John was not yet cast into prison.,nondum enim missus fuerat in carcerem Iohannes 102 | 3,25,"And there arose a question between some of John's disciples and the Jews, concerning purification.",facta est ergo quaestio ex discipulis Iohannis cum Iudaeis de purificatione 103 | 3,26,"And they came to John and said to him: Rabbi, he that was with thee beyond the Jordan, to whom thou gavest testimony: behold, he baptizeth and all men come to him.",et venerunt ad Iohannem et dixerunt ei rabbi qui erat tecum trans Iordanen cui tu testimonium perhibuisti ecce hic baptizat et omnes veniunt ad eum 104 | 3,27,"John answered and said: A man cannot receive any thing, unless it be given him from heaven.",respondit Iohannes et dixit non potest homo accipere quicquam nisi fuerit ei datum de caelo 105 | 3,28,"You yourselves do bear me witness that I said that I am not Christ, but that I am sent before him.",ipsi vos mihi testimonium perhibetis quod dixerim ego non sum Christus sed quia missus sum ante illum 106 | 3,29,"He that hath the bride is the bridegroom: but the friend of the bridegroom, who standeth and heareth Him, rejoiceth with joy because of the bridegroom's voice. This my joy therefore is fulfilled.",qui habet sponsam sponsus est amicus autem sponsi qui stat et audit eum gaudio gaudet propter vocem sponsi hoc ergo gaudium meum impletum est 107 | 3,30,He must increase: but I must decrease.,illum oportet crescere me autem minui 108 | 3,31,"He that cometh from above is above all. He that is of the earth, of the earth he is, and of the earth he speaketh. He that cometh from heaven is above all.",qui desursum venit supra omnes est qui est de terra de terra est et de terra loquitur qui de caelo venit supra omnes est 109 | 3,32,"And what he hath seen and heard, that he testifieth: and no man receiveth his testimony.",et quod vidit et audivit hoc testatur et testimonium eius nemo accipit 110 | 3,33,He that hath received his testimony hath set to his seal that God is true.,qui accipit eius testimonium signavit quia Deus verax est 111 | 3,34,For he whom God hath sent speaketh the words of God: for God doth not give the Spirit by measure.,quem enim misit Deus verba Dei loquitur non enim ad mensuram dat Deus Spiritum 112 | 3,35,The Father loveth the Son: and he hath given all things into his hand.,Pater diligit Filium et omnia dedit in manu eius 113 | 3,36,He that believeth in the Son hath life everlasting: but he that believeth not the Son shall not see life: but the wrath of God abideth on him.,qui credit in Filium habet vitam aeternam qui autem incredulus est Filio non videbit vitam sed ira Dei manet super eum 114 | 4,1,When Jesus therefore understood the Pharisees had heard that Jesus maketh more disciples and baptizeth more than John,ut ergo cognovit Iesus quia audierunt Pharisaei quia Iesus plures discipulos facit et baptizat quam Iohannes 115 | 4,2,"(Though Jesus himself did not baptize, but his disciples),",quamquam Iesus non baptizaret sed discipuli eius 116 | 4,3,He left Judea and went again into Galilee.,reliquit Iudaeam et abiit iterum in Galilaeam 117 | 4,4,And he was of necessity to pass through Samaria.,oportebat autem eum transire per Samariam 118 | 4,5,"He cometh therefore to a city of Samaria, which is called Sichar, near the land which Jacob gave to his son Joseph.",venit ergo in civitatem Samariae quae dicitur Sychar iuxta praedium quod dedit Iacob Ioseph filio suo 119 | 4,6,"Now Jacob's well was there. Jesus therefore, being wearied with his journey, sat thus on the well. It was about the sixth hour.",erat autem ibi fons Iacob Iesus ergo fatigatus ex itinere sedebat sic super fontem hora erat quasi sexta 120 | 4,7,"There cometh a woman of Samaria, to draw water. Jesus saith to her: Give me to drink.",venit mulier de Samaria haurire aquam dicit ei Iesus da mihi bibere 121 | 4,8,For his disciples were gone into the city to buy meats.,discipuli enim eius abierant in civitatem ut cibos emerent 122 | 4,9,"Then that Samaritan woman saith to him: How dost thou, being a Jew; ask of me to drink, who am a Samaritan woman? For the Jews do not communicate with the Samaritans.",dicit ergo ei mulier illa samaritana quomodo tu Iudaeus cum sis bibere a me poscis quae sum mulier samaritana non enim coutuntur Iudaei Samaritanis 123 | 4,10,"Jesus answered and said to her: If thou didst know the gift of God and who he is that saith to thee: Give me to drink; thou perhaps wouldst have asked of him, and he would have given thee living water.",respondit Iesus et dixit ei si scires donum Dei et quis est qui dicit tibi da mihi bibere tu forsitan petisses ab eo et dedisset tibi aquam vivam 124 | 4,11,"The woman saith to him: Sir, thou hast nothing wherein to draw, and the well is deep. From whence then hast thou living water?",dicit ei mulier Domine neque in quo haurias habes et puteus altus est unde ergo habes aquam vivam 125 | 4,12,"Art thou greater than our father Jacob, who gave us the well and drank thereof, himself and his children and his cattle?",numquid tu maior es patre nostro Iacob qui dedit nobis puteum et ipse ex eo bibit et filii eius et pecora eius 126 | 4,13,Jesus answered and said to her: Whosoever drinketh of this water shall thirst again: but he that shall drink of the water that I will give him shall not thirst for ever.,respondit Iesus et dixit ei omnis qui bibit ex aqua hac sitiet iterum qui autem biberit ex aqua quam ego dabo ei non sitiet in aeternum 127 | 4,14,"But the water that I will give him shall become in him a fountain of water, springing up into life everlasting.",sed aqua quam dabo ei fiet in eo fons aquae salientis in vitam aeternam 128 | 4,15,"The woman said to him: Sir, give me this water, that I may not thirst, nor come hither to draw.",dicit ad eum mulier Domine da mihi hanc aquam ut non sitiam neque veniam huc haurire 129 | 4,16,"Jesus saith to her: Go, call thy husband, and come hither.",dicit ei Iesus vade voca virum tuum et veni huc 130 | 4,17,The woman answered and said: I have no husband. Jesus said to her: Thou hast said well: I have no husband.,respondit mulier et dixit non habeo virum dicit ei Iesus bene dixisti quia non habeo virum 131 | 4,18,"For thou hast had five husbands: and he whom thou now hast is not thy husband. This, thou hast said truly.",quinque enim viros habuisti et nunc quem habes non est tuus vir hoc vere dixisti 132 | 4,19,"The woman saith to him: Sir, I perceive that thou art a prophet.",dicit ei mulier Domine video quia propheta es tu 133 | 4,20,Our fathers adored on this mountain: and you say that at Jerusalem is the place where men must adore.,patres nostri in monte hoc adoraverunt et vos dicitis quia Hierosolymis est locus ubi adorare oportet 134 | 4,21,"Jesus saith to her: Woman, believe me that the hour cometh, when you shall neither on this mountain, nor in Jerusalem, adore the Father.",dicit ei Iesus mulier crede mihi quia veniet hora quando neque in monte hoc neque in Hierosolymis adorabitis Patrem 135 | 4,22,You adore that which you know not: we adore that which we know. For salvation is of the Jews.,vos adoratis quod nescitis nos adoramus quod scimus quia salus ex Iudaeis est 136 | 4,23,"But the hour cometh and now is, when the true adorers shall adore the Father in spirit and in truth. For the Father also seeketh such to adore him.",sed venit hora et nunc est quando veri adoratores adorabunt Patrem in spiritu et veritate nam et Pater tales quaerit qui adorent eum 137 | 4,24,God is a spirit: and they that adore him must adore him in spirit and in truth.,spiritus est Deus et eos qui adorant eum in spiritu et veritate oportet adorare 138 | 4,25,"The woman saith to him: I know that the Messias cometh (who is called Christ): therefore, when he is come, he will tell us all things.",dicit ei mulier scio quia Messias venit qui dicitur Christus cum ergo venerit ille nobis adnuntiabit omnia 139 | 4,26,"Jesus saith to her: I am he, who am speaking with thee.",dicit ei Iesus ego sum qui loquor tecum 140 | 4,27,And immediately his disciples came. And they wondered that he talked with the woman. Yet no man said: What seekest thou? Or: Why talkest thou with her?,et continuo venerunt discipuli eius et mirabantur quia cum muliere loquebatur nemo tamen dixit quid quaeris aut quid loqueris cum ea 141 | 4,28,The woman therefore left her waterpot and went her way into the city and saith to the men there:,reliquit ergo hydriam suam mulier et abiit in civitatem et dicit illis hominibus 142 | 4,29,"Come, and see a man who has told me all things whatsoever I have done. Is not he the Christ?",venite videte hominem qui dixit mihi omnia quaecumque feci numquid ipse est Christus 143 | 4,30,They went therefore out of the city and came unto him.,exierunt de civitate et veniebant ad eum 144 | 4,31,"In the mean time, the disciples prayed him, saying: Rabbi, eat.",interea rogabant eum discipuli dicentes rabbi manduca 145 | 4,32,But he said to them: I have meat to eat which you know not.,ille autem dixit eis ego cibum habeo manducare quem vos nescitis 146 | 4,33,The disciples therefore said one to another: Hath any man brought him to eat?,dicebant ergo discipuli ad invicem numquid aliquis adtulit ei manducare 147 | 4,34,"Jesus saith to them: My meat is to do the will of him that sent me, that I may perfect his work.",dicit eis Iesus meus cibus est ut faciam voluntatem eius qui misit me ut perficiam opus eius 148 | 4,35,"Do not you say: There are yet four months, and then the harvest cometh? Behold, I say to you, lift up your eyes, and see the countries. For they are white already to harvest.",nonne vos dicitis quod adhuc quattuor menses sunt et messis venit ecce dico vobis levate oculos vestros et videte regiones quia albae sunt iam ad messem 149 | 4,36,And he that reapeth receiveth wages and gathereth fruit unto life everlasting: that both he that soweth and he that reapeth may rejoice together.,et qui metit mercedem accipit et congregat fructum in vitam aeternam ut et qui seminat simul gaudeat et qui metit 150 | 4,37,"For in this is the saying true: That it is one man that soweth, and it is another that reapeth.",in hoc enim est verbum verum quia alius est qui seminat et alius est qui metit 151 | 4,38,I have sent you to reap that in which you did not labour. Others have laboured: and you have entered into their labours.,ego misi vos metere quod vos non laborastis alii laboraverunt et vos in laborem eorum introistis 152 | 4,39,"Now of that city many of the Samaritans believed in him, for the word of the woman giving testimony: He told me all things whatsoever I have done.",ex civitate autem illa multi crediderunt in eum Samaritanorum propter verbum mulieris testimonium perhibentis quia dixit mihi omnia quaecumque feci 153 | 4,40,"So when the Samaritans were come to him, they desired that he would tarry there. And he abode there two days.",cum venissent ergo ad illum Samaritani rogaverunt eum ut ibi maneret et mansit ibi duos dies 154 | 4,41,"And many more believed in him, because of his own word.",et multo plures crediderunt propter sermonem eius 155 | 4,42,"And they said to the woman: We now believe, not for thy saying: for we ourselves have heard him and know that this is indeed the Saviour of the world.",et mulieri dicebant quia iam non propter tuam loquellam credimus ipsi enim audivimus et scimus quia hic est vere salvator mundi 156 | 4,43,"Now after two days, he departed thence and went into Galilee.",post duos autem dies exiit inde et abiit in Galilaeam 157 | 4,44,For Jesus himself gave testimony that a prophet hath no honour in his own country.,ipse enim Iesus testimonium perhibuit quia propheta in sua patria honorem non habet 158 | 4,45,"And when he was come into Galilee, the Galileans received him, having seen all the things he had done at Jerusalem on the festival day: for they also went to the festival day.",cum ergo venisset in Galilaeam exceperunt eum Galilaei cum omnia vidissent quae fecerat Hierosolymis in die festo et ipsi enim venerant in diem festum 159 | 4,46,"He came again therefore into Cana of Galilee, where he made the water wine. And there was a certain ruler, whose son was sick at Capharnaum.",venit ergo iterum in Cana Galilaeae ubi fecit aquam vinum et erat quidam regulus cuius filius infirmabatur Capharnaum 160 | 4,47,"He having heard that Jesus was come from Judea into Galilee, sent to him and prayed him to come down and heal his son: for he was at the point of death.",hic cum audisset quia Iesus adveniret a Iudaea in Galilaeam abiit ad eum et rogabat eum ut descenderet et sanaret filium eius incipiebat enim mori 161 | 4,48,"Jesus therefore said to him: Unless you see signs and wonders, you believe not.",dixit ergo Iesus ad eum nisi signa et prodigia videritis non creditis 162 | 4,49,"The ruler saith to him: Lord, come down before that my son die.",dicit ad eum regulus Domine descende priusquam moriatur filius meus 163 | 4,50,Jesus saith to him: Go thy way. Thy son liveth.The man believed the word which Jesus said to him and went his way.,dicit ei Iesus vade filius tuus vivitcredidit homo sermoni quem dixit ei Iesus et ibat 164 | 4,51,"And as he was going down, his servants met him: and they brought word, saying, that his son lived.",iam autem eo descendente servi occurrerunt ei et nuntiaverunt dicentes quia filius eius viveret 165 | 4,52,"He asked therefore of them the hour wherein he grew better. And they said to him: Yesterday at the seventh hour, the fever left him.",interrogabat ergo horam ab eis in qua melius habuerit et dixerunt ei quia heri hora septima reliquit eum febris 166 | 4,53,"The father therefore knew that it was at the same hour that Jesus said to him: Thy son liveth. And himself believed, and his whole house.",cognovit ergo pater quia illa hora erat in qua dixit ei Iesus filius tuus vivit et credidit ipse et domus eius tota 167 | 4,54,"This is again the second miracle that Jesus did, when he was come out of Judea. into Galilee.",hoc iterum secundum signum fecit Iesus cum venisset a Iudaea in Galilaeam -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------