[
  {
    "path": ".Rbuildignore",
    "content": "^.*\\.Rproj$\n^\\.Rproj\\.user$\npriv\nREADME_files\nREADME.md\nREADME.R\ndata-raw\nTODO.txt\nexamples\n^cran-comments\\.md$\nCODE_OF_CONDUCT.md\nLICENSE\nCONTRIBUTING.md\n^CRAN-RELEASE$\n^\\.github$\n^CRAN-SUBMISSION$\n"
  },
  {
    "path": ".github/.gitignore",
    "content": "*.html\n"
  },
  {
    "path": ".github/workflows/R-CMD-check.yaml",
    "content": "# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples\n# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help\non:\n  push:\n    branches: [main, master, devel]\n  pull_request:\n    branches: [main, master, devel]\n\nname: R-CMD-check\n\njobs:\n  R-CMD-check:\n    runs-on: ${{ matrix.config.os }}\n\n    name: ${{ matrix.config.os }} (${{ matrix.config.r }})\n\n    strategy:\n      fail-fast: false\n      matrix:\n        config:\n          - {os: macos-latest,   r: 'release'}\n          - {os: windows-latest, r: 'release'}\n          - {os: ubuntu-latest,   r: 'devel', http-user-agent: 'release'}\n          - {os: ubuntu-latest,   r: 'release'}\n          - {os: ubuntu-latest,   r: 'oldrel-1'}\n\n    env:\n      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}\n      R_KEEP_PKG_SOURCE: yes\n\n    steps:\n      - uses: actions/checkout@v3\n\n      - uses: r-lib/actions/setup-pandoc@v2\n\n      - uses: r-lib/actions/setup-r@v2\n        with:\n          r-version: ${{ matrix.config.r }}\n          http-user-agent: ${{ matrix.config.http-user-agent }}\n          use-public-rspm: true\n\n      - uses: r-lib/actions/setup-r-dependencies@v2\n        with:\n          extra-packages: any::rcmdcheck\n          needs: check\n\n      - uses: r-lib/actions/check-r-package@v2\n        with:\n          upload-snapshots: true\n          args: 'c(\"--no-manual\", \"--as-cran\")'\n"
  },
  {
    "path": ".gitignore",
    "content": "# General ---------------------------------------------------------------------\n\npriv\n# R specific ------------------------------------------------------------------\n# History files\n.Rhistory\n.Rapp.history\n# Example code in package build process\n*-Ex.R\n# RStudio files\n.Rproj.user/\n.Rproj.user\n*.Rproj\n# produced vignettes\nvignettes/*.html\nvignettes/*.pdf\n# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3\n.httr-oauth\n# cached Rmarkdown files\n*_cache\n# Rpubs\nrsconnect\ninst/doc\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment include:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at jschoeley@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "Contributing to `tricolore`\n---------------------------\n\n*This guide is adapted from the `devtools` template*\n\nThe goal of this guide is to help you contribute to `tricolore` as quickly and as easily possible. The guide is divided into two main pieces:\n\n1. Filing a bug report or feature request in an issue.\n2. Suggesting a change via a pull request.\n\n## Issues\n\nBefore you file an issue:\n\n1. Check that you're using the latest version of `tricolore`. It's quite possible that the problem you're experiencing has already been fixed.\n2. Check that the issue belongs in `tricolore`. Much functionality now lives in separate packages (e.g. `ggtern`).\n3. Spend a few minutes looking at the existing issues. It's possible that your issue has already been filed. But it's almost always better to open a new issue instead of commenting on an existing issue. The only exception is that you are confident that your issue is identical to an existing problem, and your contribution will help us better understand the general case. It's generally a bad idea to comment on a closed issue or a commit. Those comments don't show up in the issue tracker and are easily misplaced.\n\nWhen filing an issue, the most important thing is to include a minimal reproducible example so that we can quickly verify the problem, and then figure out how to fix it. There are three things you need to include to make your example reproducible: required packages, data, code.\n\n1. **Packages** should be loaded at the top of the script, so it's easy to see which ones the example needs.\n2. The easiest way to include **data** is to use `dput()` to generate the R code to recreate it. For example, to recreate the `mtcars` dataset in R, I'd perform the following steps:\n       1. Run `dput(mtcars)` in R\n       2. Copy the output\n       3. In my reproducible script, type `mtcars <- ` then paste.\n    But even better is if you can create a `data.frame()` with just a handful of rows and columns that still illustrates the problem.\n3. Spend a little bit of time ensuring that your **code** is easy for others to read:\n  * make sure you've used spaces and your variable names are concise, but informative\n  * use comments to indicate where your problem lies\n  * do your best to remove everything that is not related to the problem. The shorter your code is, the easier it is to understand.\n  * Learn a little [markdown][markdown] so you can correctly format your issue. The most important thing is to surround your code with ```` ``` R ```` and ```` ``` ```` so it's syntax highlighted (which makes it easier to read).\n4. Check that you've actually made a reproducible example by using the [reprex package](https://github.com/jennybc/reprex).\n\n## Pull requests\n\n* Your pull request will be easiest for us to read if you use a common style: <http://r-pkgs.had.co.nz/r.html#style>. Please pay particular attention to whitespace.\n\n* You should always add a bullet point to `NEWS.md` motivating the change. It should look like \"This is what changed (@yourusername, #issuenumber)\". Please don't add headings like \"bug fix\" or \"new features\" - these are added during the release process.\n\n* If you propose a new feature, write a test for it.\n\n* If you're adding new parameters or a new function, you'll also need to document them with [roxygen2](http://r-pkgs.had.co.nz/man.html). Make sure to re-run `devtools::document()` on the code before submitting.\n\nA pull request is a process, and unless you're a practised contributor it's unlikely that your pull request will be accepted as is. Typically the process looks like this:\n\n1. You submit the pull request.\n\n2. We review at a high-level and determine if this is something that we want to include in the package. If not, we'll close the pull request and suggest an alternative home for your code.\n    \n3. We'll take a closer look at the code and give you feedback.\n\n4. You respond to our feedback, update the pull request and add a comment like \"PTAL\" (please take a look). Adding the comment is important, otherwise we don't get any notification that your pull request is ready for review.\n\nDon't worry if your pull request isn't perfect. It's a learning process and we'll be happy to help you out.\n\n[markdown]: https://help.github.com/articles/basic-writing-and-formatting-syntax/"
  },
  {
    "path": "CRAN-SUBMISSION",
    "content": "Version: 1.2.4\nDate: 2024-05-14 13:32:45 UTC\nSHA: c4f25b8a52e7e6ca54bf876796e1e0f9b4432a9e\n"
  },
  {
    "path": "DESCRIPTION",
    "content": "Package: tricolore\nType: Package\nTitle: A Flexible Color Scale for Ternary Compositions\nVersion: 1.2.6\nAuthors@R: c(\n  person(\n    \"Jonas\", \"Schöley\", email = \"jschoeley@gmail.com\", role = c(\"aut\", \"cre\"),\n    comment = c(ORCID = \"0000-0002-3340-8518\")\n  ),\n  person(\n    \"Ilya\", \"Kashnitsky\", role = c(\"aut\"),\n    comment = c(ORCID = \"0000-0003-1835-8687\")\n  ))\nDescription: Compositional data consisting of three-parts can be color\n  mapped with a ternary color scale. Such a scale is provided by\n  the tricolore packages with options for discrete and continuous\n  colors, mean-centering and scaling. See \n  Jonas Schöley (2021) \"The centered ternary balance scheme. A technique\n  to visualize surfaces of unbalanced three-part compositions\"\n  <doi:10.4054/DemRes.2021.44.19>,\n  Jonas Schöley, Frans Willekens (2017) \"Visualizing compositional data\n  on the Lexis surface\" <doi:10.4054/DemRes.2017.36.21>, and\n  Ilya Kashnitsky, Jonas Schöley (2018) \"Regional population structures\n  at a glance\" <doi:10.1016/S0140-6736(18)31194-2>.\nLicense: GPL-3\nURL: https://github.com/jschoeley/tricolore\nEncoding: UTF-8\nLazyData: true\nDepends: R (>= 4.0)\nImports: grDevices, ggplot2 (>= 4.0.0), ggtern (>= 4.0.0), rlang (>= 1.1.0), shiny, assertthat\nRoxygenNote: 7.3.3\nSuggests: testthat, knitr, rmarkdown, sf, leaflet, httpuv, dplyr\nVignetteBuilder: knitr\n"
  },
  {
    "path": "LICENSE",
    "content": "### GNU GENERAL PUBLIC LICENSE\n\nVersion 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc.\n<https://fsf.org/>\n\nEveryone is permitted to copy and distribute verbatim copies of this\nlicense document, but changing it is not allowed.\n\n### Preamble\n\nThe GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom\nto share and change all versions of a program--to make sure it remains\nfree software for all its users. We, the Free Software Foundation, use\nthe GNU General Public License for most of our software; it applies\nalso to any other work released this way by its authors. You can apply\nit to your programs, too.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nTo protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you\nhave certain responsibilities if you distribute copies of the\nsoftware, or if you modify it: responsibilities to respect the freedom\nof others.\n\nFor example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\nFor the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\nSome devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the\nmanufacturer can do so. This is fundamentally incompatible with the\naim of protecting users' freedom to change the software. The\nsystematic pattern of such abuse occurs in the area of products for\nindividuals to use, which is precisely where it is most unacceptable.\nTherefore, we have designed this version of the GPL to prohibit the\npractice for those products. If such problems arise substantially in\nother domains, we stand ready to extend this provision to those\ndomains in future versions of the GPL, as needed to protect the\nfreedom of users.\n\nFinally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish\nto avoid the special danger that patents applied to a free program\ncould make it effectively proprietary. To prevent this, the GPL\nassures that patents cannot be used to render the program non-free.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n### TERMS AND CONDITIONS\n\n#### 0. Definitions.\n\n\"This License\" refers to version 3 of the GNU General Public License.\n\n\"Copyright\" also means copyright-like laws that apply to other kinds\nof works, such as semiconductor masks.\n\n\"The Program\" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as \"you\". \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\nTo \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of\nan exact copy. The resulting work is called a \"modified version\" of\nthe earlier work or a work \"based on\" the earlier work.\n\nA \"covered work\" means either the unmodified Program or a work based\non the Program.\n\nTo \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user\nthrough a computer network, with no transfer of a copy, is not\nconveying.\n\nAn interactive user interface displays \"Appropriate Legal Notices\" to\nthe extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n#### 1. Source Code.\n\nThe \"source code\" for a work means the preferred form of the work for\nmaking modifications to it. \"Object code\" means any non-source form of\na work.\n\nA \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users can\nregenerate automatically from other parts of the Corresponding Source.\n\nThe Corresponding Source for a work in source code form is that same\nwork.\n\n#### 2. Basic Permissions.\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not convey,\nwithout conditions so long as your license otherwise remains in force.\nYou may convey covered works to others for the sole purpose of having\nthem make modifications exclusively for you, or provide you with\nfacilities for running those works, provided that you comply with the\nterms of this License in conveying all material for which you do not\ncontrol copyright. Those thus making or running the covered works for\nyou must do so exclusively on your behalf, under your direction and\ncontrol, on terms that prohibit them from making any copies of your\ncopyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under the\nconditions stated below. Sublicensing is not allowed; section 10 makes\nit unnecessary.\n\n#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such\ncircumvention is effected by exercising rights under this License with\nrespect to the covered work, and you disclaim any intention to limit\noperation or modification of the work as a means of enforcing, against\nthe work's users, your or third parties' legal rights to forbid\ncircumvention of technological measures.\n\n#### 4. Conveying Verbatim Copies.\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n#### 5. Conveying Modified Source Versions.\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these\nconditions:\n\n-   a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n-   b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under\n    section 7. This requirement modifies the requirement in section 4\n    to \"keep intact all notices\".\n-   c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy. This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged. This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n-   d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n#### 6. Conveying Non-Source Forms.\n\nYou may convey a covered work in object code form under the terms of\nsections 4 and 5, provided that you also convey the machine-readable\nCorresponding Source under the terms of this License, in one of these\nways:\n\n-   a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n-   b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the Corresponding\n    Source from a network server at no charge.\n-   c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source. This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n-   d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge. You need not require recipients to copy the\n    Corresponding Source along with the object code. If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source. Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n-   e) Convey the object code using peer-to-peer transmission,\n    provided you inform other peers where the object code and\n    Corresponding Source of the work are being offered to the general\n    public at no charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal,\nfamily, or household purposes, or (2) anything designed or sold for\nincorporation into a dwelling. In determining whether a product is a\nconsumer product, doubtful cases shall be resolved in favor of\ncoverage. For a particular product received by a particular user,\n\"normally used\" refers to a typical or common use of that class of\nproduct, regardless of the status of the particular user or of the way\nin which the particular user actually uses, or expects or is expected\nto use, the product. A product is a consumer product regardless of\nwhether the product has substantial commercial, industrial or\nnon-consumer uses, unless such uses represent the only significant\nmode of use of the product.\n\n\"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to\ninstall and execute modified versions of a covered work in that User\nProduct from a modified version of its Corresponding Source. The\ninformation must suffice to ensure that the continued functioning of\nthe modified object code is in no case prevented or interfered with\nsolely because modification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or\nupdates for a work that has been modified or installed by the\nrecipient, or for the User Product in which it has been modified or\ninstalled. Access to a network may be denied when the modification\nitself materially and adversely affects the operation of the network\nor violates the rules and protocols for communication across the\nnetwork.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n#### 7. Additional Terms.\n\n\"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders\nof that material) supplement the terms of this License with terms:\n\n-   a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n-   b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n-   c) Prohibiting misrepresentation of the origin of that material,\n    or requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n-   d) Limiting the use for publicity purposes of names of licensors\n    or authors of the material; or\n-   e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n-   f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions\n    of it) with contractual assumptions of liability to the recipient,\n    for any liability that these contractual assumptions directly\n    impose on those licensors and authors.\n\nAll other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions; the\nabove requirements apply either way.\n\n#### 8. Termination.\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your license\nfrom a particular copyright holder is reinstated (a) provisionally,\nunless and until the copyright holder explicitly and finally\nterminates your license, and (b) permanently, if the copyright holder\nfails to notify you of the violation by some reasonable means prior to\n60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n#### 9. Acceptance Not Required for Having Copies.\n\nYou are not required to accept this License in order to receive or run\na copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n#### 10. Automatic Licensing of Downstream Recipients.\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n#### 11. Patents.\n\nA \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's \"contributor version\".\n\nA contributor's \"essential patent claims\" are all patent claims owned\nor controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is \"discriminatory\" if it does not include within the\nscope of its coverage, prohibits the exercise of, or is conditioned on\nthe non-exercise of one or more of the rights that are specifically\ngranted under this License. You may not convey a covered work if you\nare a party to an arrangement with a third party that is in the\nbusiness of distributing software, under which you make payment to the\nthird party based on the extent of your activity of conveying the\nwork, and under which the third party grants, to any of the parties\nwho would receive the covered work from you, a discriminatory patent\nlicense (a) in connection with copies of the covered work conveyed by\nyou (or copies made from those copies), or (b) primarily for and in\nconnection with specific products or compilations that contain the\ncovered work, unless you entered into that arrangement, or that patent\nlicense was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n#### 12. No Surrender of Others' Freedom.\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under\nthis License and any other pertinent obligations, then as a\nconsequence you may not convey it at all. For example, if you agree to\nterms that obligate you to collect a royalty for further conveying\nfrom those to whom you convey the Program, the only way you could\nsatisfy both those terms and this License would be to refrain entirely\nfrom conveying the Program.\n\n#### 13. Use with the GNU Affero General Public License.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n#### 14. Revised Versions of this License.\n\nThe Free Software Foundation may publish revised and/or new versions\nof the GNU General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in\ndetail to address new problems or concerns.\n\nEach version is given a distinguishing version number. If the Program\nspecifies that a certain numbered version of the GNU General Public\nLicense \"or any later version\" applies to it, you have the option of\nfollowing the terms and conditions either of that numbered version or\nof any later version published by the Free Software Foundation. If the\nProgram does not specify a version number of the GNU General Public\nLicense, you may choose any version ever published by the Free\nSoftware Foundation.\n\nIf the Program specifies that a proxy can decide which future versions\nof the GNU General Public License can be used, that proxy's public\nstatement of acceptance of a version permanently authorizes you to\nchoose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n#### 15. Disclaimer of Warranty.\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT\nWARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND\nPERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE\nDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR\nCORRECTION.\n\n#### 16. Limitation of Liability.\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR\nCONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES\nARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT\nNOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR\nLOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM\nTO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER\nPARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n#### 17. Interpretation of Sections 15 and 16.\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\nEND OF TERMS AND CONDITIONS\n\n### How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these\nterms.\n\nTo do so, attach the following notices to the program. It is safest to\nattach them to the start of each source file to most effectively state\nthe exclusion of warranty; and each file should have at least the\n\"copyright\" line and a pointer to where the full notice is found.\n\n        <one line to give the program's name and a brief idea of what it does.>\n        Copyright (C) <year>  <name of author>\n\n        This program is free software: you can redistribute it and/or modify\n        it under the terms of the GNU General Public License as published by\n        the Free Software Foundation, either version 3 of the License, or\n        (at your option) any later version.\n\n        This program is distributed in the hope that it will be useful,\n        but WITHOUT ANY WARRANTY; without even the implied warranty of\n        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n        GNU General Public License for more details.\n\n        You should have received a copy of the GNU General Public License\n        along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper\nmail.\n\nIf the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n        <program>  Copyright (C) <year>  <name of author>\n        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n        This is free software, and you are welcome to redistribute it\n        under certain conditions; type `show c' for details.\n\nThe hypothetical commands \\`show w' and \\`show c' should show the\nappropriate parts of the General Public License. Of course, your\nprogram's commands might be different; for a GUI interface, you would\nuse an \"about box\".\n\nYou should also get your employer (if you work as a programmer) or\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary. For more information on this, and how to apply and follow\nthe GNU GPL, see <https://www.gnu.org/licenses/>.\n\nThe GNU General Public License does not permit incorporating your\nprogram into proprietary programs. If your program is a subroutine\nlibrary, you may consider it more useful to permit linking proprietary\napplications with the library. If this is what you want to do, use the\nGNU Lesser General Public License instead of this License. But first,\nplease read <https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "NAMESPACE",
    "content": "# Generated by roxygen2: do not edit by hand\n\nexport(DemoTricolore)\nexport(Tricolore)\nexport(TricoloreSextant)\nimportFrom(assertthat,assert_that)\nimportFrom(assertthat,is.flag)\nimportFrom(assertthat,is.number)\nimportFrom(assertthat,is.scalar)\nimportFrom(assertthat,is.string)\nimportFrom(ggplot2,element_text)\nimportFrom(ggplot2,labs)\nimportFrom(ggplot2,layer)\nimportFrom(ggplot2,scale_color_identity)\nimportFrom(ggplot2,scale_fill_identity)\nimportFrom(ggplot2,theme)\nimportFrom(ggtern,aes)\nimportFrom(ggtern,geom_Lline)\nimportFrom(ggtern,geom_Rline)\nimportFrom(ggtern,geom_Tline)\nimportFrom(ggtern,geom_mask)\nimportFrom(ggtern,ggtern)\nimportFrom(ggtern,scale_L_continuous)\nimportFrom(ggtern,scale_R_continuous)\nimportFrom(ggtern,scale_T_continuous)\nimportFrom(ggtern,theme_classic)\nimportFrom(grDevices,hcl)\nimportFrom(grDevices,hsv)\nimportFrom(rlang,.data)\n"
  },
  {
    "path": "NEWS.md",
    "content": "# tricolore 1.2.6\n\n* establish compatibility with ggplot/ggtern 4.0.0\n\n# tricolore 1.2.5\n\n* re-export `euro_basemap.RData` to fix (@clementviolet, #24)\n\n# tricolore 1.2.4\n\n* establish compatibility with ggplot/ggtern 3.4.2\n* update deprecated ggplot code\n* update outdated crs spec in example data\n* add Schöley (2021) reference to vignette\n\n# tricolore 1.2.3\n\n* add startup message and citation information\n* establish compatibility with ggplot2 3.3.4/3.3.5 (@hhmacedo, #13)\n\n# tricolore 1.2.2\n\n* establish compatibility with ggplot/ggtern 3.3.0\n* remove 'caption' labels from example plots as it causes rendering bug\n\n# tricolore 1.2.1\n\n* establish compatibility with ggplot/ggtern 3.2.0\n* allow TricoloreDemo() to run as stand-alone shiny-app (i.e. on shinyapps server)\n\n# tricolore 1.2.0\n\n* allow for discrete re-centered scales\n* add new discrete scales TricoloreSextant\n* reorder Tricolore*() arguments\n* rename Tricolore*() list output to `rgb` and `key`\n* add new features to shiny app\n\n# tricolore 1.1.1\n\n* make TernaryLimits() internal\n\n# tricolore 1.1.0\n\n* change defaults\n* make defaults dynamic\n* remove alpha part from rgb codes\n\n# tricolore 1.0.8\n\n* add legend crop option\n* update README\n* add dependencies to travis recipe\n\n# tricolore 1.0.7\n\n* add dependencies to travis recipe\n\n# tricolore 1.0.6\n\n* provide example data as sf data frame\n* use sf in the examples\n* add choropleth maps with tricolore vignette featuring leaflets\n\n# tricolore 1.0.5\n\n* add option for percent-point difference labeling in ternary legend\n* add tests\n\n# tricolore 1.0.4\n\n* establish compatibility with ggplot/ggtern 3.0.0\n\n# tricolore 1.0.3\n\n* Initial CRAN release\n"
  },
  {
    "path": "R/tricolore.R",
    "content": "# Misc --------------------------------------------------------------------\n\n# from nnet::which.is.max()\nMaxIndex <- function (x) {\n  y <- seq_along(x)[x == max(x)]\n  if (length(y) > 1L) { sample(y, 1L) } else { y }\n}\n\n#' Validate Main Arguments\n#'\n#' Validate main arguments of tricolore function.\n#'\n#' @param df Data frame of compositions.\n#' @param p1 Column name for variable in df giving first proportion\n#'           of ternary composition (string).\n#' @param p2 Column name for variable in df giving second proportion\n#'           of ternary composition (string.\n#' @param p3 Column name for variable in df giving third proportion\n#'           of ternary composition (string).\n#'\n#' @importFrom assertthat assert_that is.string\n#'\n#' @keywords internal\nValidateMainArguments <- function (df, p1, p2, p3) {\n\n  # missing arguments\n  assert_that(!missing(df), !missing(p1), !missing(p2), !missing(p3),\n              msg = 'main argument missing')\n  # compositional data is data frame\n  assert_that(is.data.frame(df))\n  # variable names as strings\n  assert_that(is.string(p1), is.string(p2), is.string(p3))\n  # missing variables in data frame\n  assert_that(p1 %in% names(df), msg = paste('variable', p1 ,'not found in df'))\n  assert_that(p2 %in% names(df), msg = paste('variable', p2 ,'not found in df'))\n  assert_that(p3 %in% names(df), msg = paste('variable', p3 ,'not found in df'))\n  # compositional data is numeric\n  assert_that(is.numeric(df[[p1]]), msg = paste('variable', p1 ,'is not numeric'))\n  assert_that(is.numeric(df[[p2]]), msg = paste('variable', p2 ,'is not numeric'))\n  assert_that(is.numeric(df[[p3]]), msg = paste('variable', p3 ,'is not numeric'))\n  # compositional data is not negative\n  assert_that(!any(df[[p1]] < 0, na.rm = TRUE),\n              msg = paste('variable', p1 ,'contains negative values'))\n  assert_that(!any(df[[p2]] < 0, na.rm = TRUE),\n              msg = paste('variable', p2 ,'contains negative values'))\n  assert_that(!any(df[[p3]] < 0, na.rm = TRUE),\n              msg = paste('variable', p3 ,'contains negative values'))\n  # NA, Inf, NaN are allowed and are expected to return NA as color\n\n}\n\n#' Validate Shared Parameters\n#'\n#' Validate parameters shared across tricolore functions.\n#'\n#' @param pars A named list of parameters.\n#'\n#' @importFrom assertthat assert_that is.scalar is.flag\n#'\n#' @keywords internal\nValidateParametersShared <- function (pars) {\n\n  with(pars, {\n    # center either NA or three element numeric vector\n    # with sum 1 and elements > 0\n    assert_that((is.scalar(center) && is.na(center)) ||\n                  (length(center) == 3L &&\n                     all(is.numeric(center)) &&\n                     sum(center) == 1 &&\n                     all(center != 0)),\n                msg = 'center must be either NA or a three element numeric vector with sum == 1 and all element > 0.')\n    # flags\n    assert_that(is.flag(legend), is.flag(show_data),\n                is.flag(show_center), is.flag(crop))\n    # character options\n    assert_that(is.scalar(label_as),\n                is.character(label_as),\n                label_as %in% c('pct', 'pct_diff'),\n                msg = 'label_as must be either \"pct\" or \"pct_diff\".')\n  })\n\n}\n\n#' Validate Tricolore Parameters\n#'\n#' Validate parameters of Tricolore function.\n#'\n#' @param pars A named list of parameters.\n#'\n#' @importFrom assertthat assert_that is.number is.scalar\n#'\n#' @keywords internal\nValidateParametersTricolore <- function (pars) {\n\n  # a modified version of assertthat::is.count that regards\n  # infinite values as counts\n  is.count2 <- function (x) {\n    if (length(x) != 1) return(FALSE)\n    integerish <- is.integer(x) || (is.numeric(x) && (x == trunc(x)))\n    if (!integerish) return(FALSE)\n    x > 0\n  }\n\n  with(pars, {\n    # breaks is count scalar > 1 (can't use is.count() because\n    # it throws an error when encountering infinite values)\n    assert_that(is.scalar(breaks), is.count2(breaks), breaks > 1)\n    # hue is numeric scalar in range [0, 1]\n    assert_that(is.number(hue), hue >= 0 && hue <= 1)\n    # chroma is numeric scalar in range [0, 1]\n    assert_that(is.number(chroma), chroma >= 0 && chroma <= 1)\n    # lightness is numeric scalar in range [0, 1]\n    assert_that(is.number(lightness), lightness >= 0 && lightness <= 1)\n    # contrast is numeric scalar in range [0, 1]\n    assert_that(is.number(contrast), contrast >= 0 && contrast <= 1)\n    # spread is positive numeric scalar\n    assert_that(is.number(spread), spread > 0, is.finite(spread))\n  })\n\n  ValidateParametersShared(pars)\n\n}\n\n#' Validate TricoloreSextant Parameters\n#'\n#' Validate parameters of TricoloreSextant function.\n#'\n#' @param pars A named list of parameters.\n#'\n#' @importFrom assertthat assert_that is.number is.scalar\n#'\n#' @keywords internal\nValidateParametersTricoloreSextant <- function (pars) {\n\n  with(pars, {\n    assert_that(is.character(values), length(values) == 6)\n  })\n\n  ValidateParametersShared(pars)\n\n}\n\n# Compositional Data Analysis ---------------------------------------------\n\n#' Geometric Mean\n#'\n#' Calculate the geometric mean for a numeric vector.\n#'\n#' @param x Numeric vector.\n#' @param na.rm Should NAs be removed? (default=TRUE)\n#' @param zero.rm Should zeros be removed? (default=TRUE)\n#'\n#' @return The geometric mean as numeric scalar.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' tricolore:::GeometricMean(0:100)\n#' tricolore:::GeometricMean(0:100, zero.rm = FALSE)\n#'\n#' @keywords internal\nGeometricMean <- function (x, na.rm = TRUE, zero.rm = TRUE) {\n  # the geometric mean can't really deal with elements equal to 0\n  # this option removes 0 elements from the vector\n  if (zero.rm) { x <- x[x!=0] }\n  return(exp(mean(log(x), na.rm = na.rm)))\n}\n\n#' Compositional Centre\n#'\n#' Calculate the centre of a compositional data set.\n#'\n#' @param P n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.\n#'\n#' @return The centre of P as an m element numeric vector.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' P <- prop.table(matrix(runif(300), 100), margin = 1)\n#' tricolore:::Centre(P)\n#'\n#' @references\n#' Von Eynatten, H., Pawlowsky-Glahn, V., & Egozcue, J. J. (2002).\n#' Understanding perturbation on the simplex: A simple method to better\n#' visualize and interpret compositional data in ternary diagrams.\n#' Mathematical Geology, 34(3), 249-257.\n#'\n#' Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture\n#' Notes on Compositional Data Analysis. Retrieved from\n#' https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf\n#'\n#' @keywords internal\nCentre <- function (P) {\n  # calculate the geometric mean for each element of the composition\n  g <- apply(P, MARGIN = 2, FUN = GeometricMean)\n  # the closed vector of geometric means is the mean (centre)\n  # of the compositional data set\n  return(g/sum(g))\n}\n\n#' Compositional Pertubation\n#'\n#' Pertubate a compositional data set by a compositional vector.\n#'\n#' @param P n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.\n#' @param c Compositional pertubation vector [c1, ..., cm].\n#'\n#' @return n by m matrix of pertubated compositions.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' P <- prop.table(matrix(runif(12), 4), margin = 1)\n#' cP <- tricolore:::Pertube(P, 1/tricolore:::Centre(P))\n#' tricolore:::Centre(cP)\n#'\n#' @references\n#' Von Eynatten, H., Pawlowsky-Glahn, V., & Egozcue, J. J. (2002).\n#' Understanding perturbation on the simplex: A simple method to better\n#' visualize and interpret compositional data in ternary diagrams.\n#' Mathematical Geology, 34(3), 249-257.\n#'\n#' Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture\n#' Notes on Compositional Data Analysis. Retrieved from\n#' https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf\n#'\n#' @keywords internal\nPertube <- function (P, c = rep(1/3, 3)) {\n  return(prop.table(t(t(P)*c), margin = 1))\n}\n\n#' Compositional Powering\n#'\n#' Raise a compositional data-set to a given power.\n#'\n#' @param P n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.\n#' @param scale Power scalar.\n#'\n#' @return n by m numeric matrix of powered compositions.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' P <- prop.table(matrix(runif(12), 4), margin = 1)\n#' tricolore:::PowerScale(P, 2)\n#'\n#' @references\n#' Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture\n#' Notes on Compositional Data Analysis. Retrieved from\n#' https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf\n#'\n#' @keywords internal\nPowerScale <- function (P, scale = 1) {\n  return(prop.table(P^scale, margin = 1))\n}\n\n# Ternary Geometry --------------------------------------------------------\n\n# T(K=k^2):   Equilateral triangle subdivided into K equilateral sub-triangles.\n#             Each side of T is divided into k intervals of equal length.\n# (p1,p2,p3): Barycentric coordinates wrt. T(K).\n# id:         One-dimensional index of sub-triangles in T(K).\n#\n#                  p2           id index\n#                  /\\               9\n#                 /  \\            6 7 8\n#                /____\\         1 2 3 4 5\n#              p1      p3\n\n#' Centroid Coordinates of Sub-Triangles in Segmented Equilateral Triangle\n#'\n#' Segment an equilateral triangle into k^2 equilateral sub-triangles and return\n#' the barycentric centroid coordinates of each sub-triangle.\n#'\n#' @param k Number of rows in the segmented equilateral triangle.\n#'\n#' @return A numeric matrix of with index and barycentric centroid coordinates\n#'   of regions id=1,...,k^2.\n#'\n#' @references\n#' S. H. Derakhshan and C. V. Deutsch (2009): A Color Scale for Ternary Mixtures.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' tricolore:::TernaryMeshCentroids(1)\n#' tricolore:::TernaryMeshCentroids(2)\n#' tricolore:::TernaryMeshCentroids(3)\n#'\n#' @keywords internal\nTernaryMeshCentroids <- function (k) {\n  # total number of centroids and centroid id\n  K = k^2; id = 1:K\n\n  # centroid coordinates as function of K and id\n  g <- floor(sqrt(K-id)); gsq <- g^2\n  c1 <- (((-K + id + g*(g+2) + 1) %% 2) - 3*gsq - 3*id + 3*K + 1) / (6*k)\n  c2 <- -(((-K + gsq + id + 2*g + 1) %% 2) + 3*g - 3*k + 1) / (3*k)\n  c3 <- (((-K + gsq + id + 2*g + 1) %% 2) + 3*gsq + 6*g + 3*id - 3*K + 1) / (6*k)\n\n  return(cbind(id = id, p1 = c1, p2 = c2, p3 = c3))\n}\n\n#' Vertex Coordinates of Sub-Triangles in Segmented Equilateral Triangle\n#'\n#' Given the barycentric centroid coordinates of the sub-triangles in an\n#' equilateral triangle subdivided into k^2 equilateral sub-triangles, return\n#' the barycentric vertex coordinates of each sub-triangle.\n#'\n#' @param C n by 4 matrix of barycentric centroid coordinates of n=k^2\n#'          sub-triangles. Column order: id, p1, p2, p3 with id=1,...,k^2.\n#'\n#' @return A numeric matrix with index, vertex id and barycentric vertex\n#'   coordinates for each of the k^2 sub-triangles.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' k = 2\n#' C <- tricolore:::TernaryMeshCentroids(k)\n#' tricolore:::TernaryMeshVertices(C)\n#'\n#' @references\n#' S. H. Derakhshan and C. V. Deutsch (2009): A Color Scale for Ternary Mixtures.\n#'\n#' @keywords internal\nTernaryMeshVertices <- function (C) {\n  k <- sqrt(nrow(C))\n  j <- k - floor(sqrt(k^2-C[,1]))\n  i <- C[,1] - (j-1)*(2*k-j+1)\n  term1 <- ((-1)^(i %% 2) * 2) / (3*k)\n  term2 <- ((-1)^(i %% 2)) / (3*k)\n\n  v1 <- cbind(C[,2] - term1, C[,3] + term2, C[,4] + term2)\n  v2 <- cbind(C[,2] + term2, C[,3] - term1, C[,4] + term2)\n  v3 <- cbind(C[,2] + term2, C[,3] + term2, C[,4] - term1)\n\n  V <- cbind(C[,1], rep(1:3, each = nrow(C)), rbind(v1, v2, v3))\n  colnames(V) <- c('id', 'vertex', 'p1', 'p2', 'p3')\n\n  return(V)\n}\n\n#' Distance Between Points in Ternary Coordinates\n#'\n#' The distances between ternary coordinate p and a set of ternary coordinates C.\n#'\n#' @param p A vector of ternary coordinates [p1, p2, p3].\n#' @param C n by 3 matrix of ternary coordinates [p1, p2, p3](i) for i=1,...,n.\n#'\n#' @return A numeric vector of distances between coordinate p and all\n#'   coordinates in C.\n#'\n#' @references\n#' https://en.wikipedia.org/wiki/Barycentric_coordinate_system#Distance_between_points\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' p <- c(0.5, 0.2, 0.3)\n#' C <- prop.table(matrix(runif(3*10), ncol = 3), 1)\n#' tricolore:::TernaryDistance(p, C)\n#'\n#' @keywords internal\nTernaryDistance <- function(p, C) {\n  Q <- t(p-t(C))\n  return(-Q[,2]*Q[,3]-Q[,3]*Q[,1]-Q[,1]*Q[,2])\n}\n\n#' For Ternary Coordinates P Return the Nearest Coordinate in Set C\n#'\n#' @param P,C n by 3 matrix of ternary coordinates [p1, p2, p3](i) for\n#'            i=1,...,n. n may be different for P and C.\n#'\n#' @return n by 3 matrix of ternary coordinates in C.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' P <- prop.table(matrix(runif(9), ncol = 3), 1)\n#' C <- tricolore:::TernaryMeshCentroids(2)[,-1]\n#' tricolore:::TernaryNearest(P, C)\n#'\n#' @keywords internal\nTernaryNearest <- function (P, C) {\n  id <- apply(P, 1, function (x) MaxIndex(-TernaryDistance(x, C)))\n  return(C[id,])\n}\n\n#' Return Ternary Gridlines Centered Around Some Composition\n#'\n#' @param center The center of the grid.\n#'   A vector of ternary coordinates [p1, p2, p3].\n#' @param spacing The spacing of the grid in percent-point increments.\n#'   A numeric > 0.\n#'\n#' @return A list of lists.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' tricolore:::TernaryCenterGrid(c(1/6, 2/6, 3/6), 10)\n#'\n#' @keywords internal\nTernaryCenterGrid <- function (center, spacing) {\n\n  # -1 to 1 by spacing/100 with 0 point\n  div_seq <- seq(0, 1, spacing/100)\n  div_seq <- c(-rev(div_seq), div_seq[-1])\n\n  # proportion difference from center for all three ternary axes.\n  # keep only possible values\n  div_seq <- list(\n    p1 = div_seq[div_seq >= -center[1] & div_seq <= 1-center[1]],\n    p2 = div_seq[div_seq >= -center[2] & div_seq <= 1-center[2]],\n    p3 = div_seq[div_seq >= -center[3] & div_seq <= 1-center[3]]\n  )\n\n  # percent-point difference from center composition\n  labels <- lapply(div_seq, function(x) formatC(x*100, flag = '+'))\n  # label center point as percent share\n  center_pct <- paste0(formatC(center*100, digits = 1, format = 'f'), '%')\n  labels[['p1']][labels[['p1']] == '-0'] <- center_pct[1]\n  labels[['p2']][labels[['p2']] == '-0'] <- center_pct[2]\n  labels[['p3']][labels[['p3']] == '-0'] <- center_pct[3]\n\n\n  # breaks in ternary coordinates\n  breaks <- list(\n    p1 = div_seq[['p1']] + center[1],\n    p2 = div_seq[['p2']] + center[2],\n    p3 = div_seq[['p3']] + center[3]\n  )\n\n  return(list(breaks = breaks, labels = labels))\n}\n\n#' Return the Limits of Ternary Coordinates\n#'\n#' @param P n by 3 matrix of ternary coordinates [p1, p2, p3](i) for\n#'          i=1,...,n.\n#' @param na.rm Should NAs be removed? (default=TRUE)\n#'\n#' @return A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' P <- prop.table(matrix(runif(9), ncol = 3), 1)\n#' tricolore:::TernaryLimits(P)\n#'\n#' @keywords internal\nTernaryLimits <- function (P, na.rm = TRUE) {\n  limits <- matrix(NA, nrow = 2, ncol = 3,\n                   dimnames = list(c('lower', 'upper'),\n                                   c('p1', 'p2', 'p3')))\n  limits[1,] <- apply(P, 2, min, na.rm = na.rm)\n  limits[2,] <- c(1 - (limits[1,2] + limits[1,3]),\n                  1 - (limits[1,1] + limits[1,3]),\n                  1 - (limits[1,1] + limits[1,2]))\n  return(limits)\n}\n\n#' Vertex Coordinates of Sextants in Equilateral Triangle\n#'\n#' Given a barycentric center coordinate return the vertex coordinates of the\n#' of the sextant regions.\n#'\n#' @param center The sextant center.\n#'   A vector of ternary coordinates [p1, p2, p3].\n#'\n#' @return Index, vertex id and barycentric vertex coordinates for each of the\n#'         6 sextants.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' tricolore:::TernarySextantVertices(rep(1/3, 3))\n#'\n#' @keywords internal\nTernarySextantVertices <- function (center) {\n\n  # define corner points\n  p1 = c(1, 0, 0); p2 = c(0, 1, 0); p3 = c(0, 0, 1)\n  a1 <- c(center[1], 1-center[1], 0); a2 <- c(center[1], 0, 1-center[1])\n  b1 <- c(0, center[2], 1-center[2]); b2 <- c(1-center[2], center[2], 0)\n  c1 <- c(1-center[3], 0, center[3]); c2 <- c(0, 1-center[3], center[3])\n\n  # ternary sextant vertices\n  V <- cbind(\n    id =\n      c(rep(1, 5), rep(2, 4),\n        rep(3, 5), rep(4, 4),\n        rep(5, 5), rep(6, 4)),\n    vertex = rep(c(1:5, 1:4), 3),\n    matrix(\n      c(center, c1, p1, b2, center, # 1\n        center, b2, a1, center,     # 2\n        center, a1, p2, c2, center, # 3\n        center, c2, b1, center,     # 4\n        center, b1, p3, a2, center, # 5\n        center, a2, c1, center),    # 6\n      ncol = 3, nrow = 27, byrow = TRUE,\n      dimnames = list(NULL, c('p1', 'p2', 'p3'))\n    )\n  )\n\n  return(V)\n\n}\n\n#' Return Surrounding Sextant of Barycentric Coordinates\n#'\n#' Given barycentric coordinates return the id of the surrounding sextant.\n#'\n#' @param P n by 3 matrix of ternary coordinates [p1, p2, p3](i) for\n#'          i=1,...,n.\n#' @param center The sextant center.\n#'   A vector of ternary coordinates [p1, p2, p3].\n#'\n#' @return An n element character vector of sextant id's 1 to 6.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' P <- prop.table(matrix(runif(9), ncol = 3), 1)\n#' tricolore:::TernarySurroundingSextant(P, rep(1/3, 3))\n#'\n#' @keywords internal\nTernarySurroundingSextant <- function (P, center) {\n  # six cases, six sextants, NA if at center or NA in input\n  is_larger <- t(t(P) > center)\n  id <- apply(is_larger, 1, function (x) {\n    y <- NA\n    if (identical(x, c(TRUE, FALSE, FALSE))) y <- 1\n    if (identical(x, c(TRUE, TRUE, FALSE)))  y <- 2\n    if (identical(x, c(FALSE, TRUE, FALSE))) y <- 3\n    if (identical(x, c(FALSE, TRUE, TRUE)))  y <- 4\n    if (identical(x, c(FALSE, FALSE, TRUE))) y <- 5\n    if (identical(x, c(TRUE, FALSE, TRUE)))  y <- 6\n    y\n  })\n  return(id)\n}\n\n# Ternary Color Maps ------------------------------------------------------\n\n#' CIE-Lch Mixture of Ternary Composition\n#'\n#' Return the ternary balance scheme colors for a matrix of ternary compositions.\n#'\n#' @param P n by 3 matrix of ternary compositions [p1, p2, p3](i) for\n#'          i=1, ..., n.\n#' @param center Ternary coordinates of the grey-point.\n#' @param breaks Number of breaks in the discrete color scale. An integer >1.\n#'               Values above 99 imply no discretization.\n#' @param h_ Primary hue of the first ternary element in angular degrees [0, 360].\n#' @param c_ Maximum possible chroma of mixed colors [0, 200].\n#' @param l_ Lightness of mixed colors [0, 100].\n#' @param contrast Lightness contrast of the color scale [0, 1).\n#' @param spread Spread of the color scale around center > 0.\n#'\n#' @return An n row data frame giving, for each row of the input P, the input\n#' proportions [p1, p2, p3], parameters of the color mixture (h, c, l) and the\n#' hex-rgb string of the mixed colors (rgb).\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' P <- prop.table(matrix(runif(9), ncol = 3), 1)\n#' tricolore:::ColorMapTricolore(P, center = rep(1/3, 3), breaks = 4,\n#'                               h_ = 80, c_ = 140, l_ = 80,\n#'                               contrast = 0.4, spread = 1)\n#'\n#' @importFrom grDevices hcl hsv\n#'\n#' @keywords internal\nColorMapTricolore <- function (P, center, breaks, h_, c_, l_, contrast, spread) {\n\n  ### Discretize ###\n\n  # closing (copy of closed, non-transformed input data for output)\n  P <- P_notrans <- prop.table(P, margin = 1)\n\n  # discretize to nearest ternary mesh centroid\n  # don't discretize if breaks > 99 to avoid expensive calculations\n  # which don't make much of a difference in output\n  if (breaks < 100) {\n    P <- TernaryNearest(P, TernaryMeshCentroids(breaks)[,-1])\n  }\n\n  ### Center and scale ###\n\n  # centering\n  P <- Pertube(P, 1/center)\n  # scaling\n  P <- PowerScale(P, spread)\n\n  ### Colorize ###\n\n  # calculate the chroma matrix C by scaling the row proportions\n  # of the input matrix P by the maximum chroma parameter.\n  C <- P*c_\n\n  # generate primary colors starting with a hue value in [0, 360) and then\n  # picking two equidistant points on the circumference of the color wheel.\n  # input hue in degrees, all further calculations in radians.\n  phi <- (h_*0.0174 + c(0, 2.09, 4.19)) %% 6.28\n\n  # the complex matrix Z represents each case (i) and group (j=1,2,3) specific\n  # color in complex polar form with hue as angle and chroma as radius.\n  Z <- matrix(complex(argument = phi, modulus = c(t(C))),\n              ncol = 3, byrow = TRUE)\n\n  # adding up the rows gives the CIE-Lab (cartesian) coordinates\n  # of the convex color mixture in complex form.\n  z <- rowSums(Z)\n  # convert the cartesian CIE-Lab coordinates to polar CIE-Luv coordinates\n  # and add lightness level.\n  M <- cbind(h = (Arg(z)*57.3)%%360, c = Mod(z), l = l_)\n\n  # decrease lightness and chroma towards the center of the color scale\n  cfactor <- M[,2]*contrast/c_ + 1-contrast\n  M[,3] <- cfactor*M[,3]\n  M[,2] <- cfactor*M[,2]\n\n  # convert the complex representation of the color mixture to\n  # hex-srgb representation via the hcl (CIE-Luv) color space\n  rgb <- hcl(h = M[,1], c = M[,2], l = M[,3],\n             alpha = 1, fixup = TRUE)\n  # remove alpha information\n  rgb <- substr(rgb, 1, 7)\n\n  ### Output ###\n\n  # non-transformed compositions, hcl values of mixtures and rgb code\n  result <- data.frame(P_notrans, M[,1], M[,2], M[,3], rgb,\n                       row.names = NULL, check.rows = FALSE,\n                       check.names = FALSE, stringsAsFactors = FALSE)\n  colnames(result) <- c('p1', 'p2', 'p3', 'h', 'c', 'l', 'rgb')\n  return(result)\n}\n\n#' Sextant Encoding of Ternary Composition\n#'\n#' Return the sextant scheme colors for a matrix of ternary compositions.\n#'\n#' @param P n by 3 matrix of ternary compositions [p1, p2, p3](i) for\n#'          i=1, ..., n.\n#' @param center Ternary coordinates of the sextant meeting point.\n#' @param values 6 element character vector of rgb-codes.\n#'\n#' @return An n row data frame giving, for each row of the input P, the input\n#' proportions [p1, p2, p3], sextant id (sextant) and the hex-rgb string of the\n#' mixed colors (rgb).\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' P <- prop.table(matrix(runif(9), ncol = 3), 1)\n#' tricolore:::ColorMapSextant(P, c(1/3, 1/3, 1/3),\n#'                             c('#01A0C6', '#B8B3D8', '#F11D8C', '#FFB3B3',\n#'                               '#FFFF00', '#B3DCC3'))\n#' @keywords internal\nColorMapSextant <- function (P, center, values) {\n  # close composition\n  P <- prop.table(P, margin = 1)\n\n  # assign points to sextants and corresponding color codes\n  sextant <- TernarySurroundingSextant(P, center)\n  rgb <- values[sextant]\n\n  # non-transformed compositions, sextant id and hexsrgb code\n  result <- data.frame(P, sextant, rgb,\n                       row.names = NULL, check.rows = FALSE,\n                       check.names = FALSE, stringsAsFactors = FALSE)\n  colnames(result) <- c('p1', 'p2', 'p3', 'sextant', 'rgb')\n  return(result)\n}\n\n# Ternary Color Keys ------------------------------------------------------\n\n#' Breaks and Labels for Ternary Color Key\n#'\n#' Return various types of breaks and labels for ternary color keys.\n#'\n#' @param type   An integer 1, 2, or 3.\n#' @param center Ternary coordinates of the grey-point.\n#' @param breaks Number of breaks in the discrete color scale. An integer >1.\n#'               Values above 99 imply no discretization.\n#'\n#' @return A list of lists containing breaks and labels for each of the 3\n#'   ternary axes.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' tricolore:::BreaksAndLabels(1, breaks = 3)\n#' tricolore:::BreaksAndLabels(2)\n#' tricolore:::BreaksAndLabels(3, center = c(1/3, 1/3, 1/3))\n#'\n#' @keywords internal\nBreaksAndLabels <- function (type, center = NULL, breaks = NULL) {\n  brk_lab <-\n    switch(type,\n           list(breaks = list(p1 = seq(0, 1, length.out = breaks+1),\n                              p2 = seq(0, 1, length.out = breaks+1),\n                              p3 = seq(0, 1, length.out = breaks+1)),\n                labels = list(p1 = round(seq(0, 1, length.out = breaks+1)*100, 1),\n                              p2 = round(seq(0, 1, length.out = breaks+1)*100, 1),\n                              p3 = round(seq(0, 1, length.out = breaks+1)*100, 1))),\n           list(breaks = list(p1 = c(0.25, 0.5, 0.75),\n                              p2 = c(0.25, 0.5, 0.75),\n                              p3 = c(0.25, 0.5, 0.75)),\n                labels = list(p1 = c('25', '50', '75'),\n                              p2 = c('25', '50', '75'),\n                              p3 = c('25', '50', '75'))),\n           TernaryCenterGrid(center = center, spacing = 10)\n    )\n  return(brk_lab)\n}\n\n#' Template for Ternary Key\n#'\n#' Return various types of breaks and labels for ternary color keys.\n#'\n#' @param legend_surface A data frame with numeric 'id', 'p1', 'p2', 'p3' and\n#'                       character column 'rgb'.\n#' @param limits A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.\n#' @param brklab Breaks and labels as returned by \\code{\\link{BreaksAndLabels}}.\n#' @param show_center Should the center be marked on the legend? (logical)\n#' @param center Ternary coordinates of the grey-point.\n#' @param lwd A numeric scalar giving the linewidth of the legend surface\n#'            polygons.\n#'\n#' @return A ggtern grob.\n#'\n#' @importFrom ggplot2 scale_color_identity\n#'   scale_fill_identity element_text theme layer\n#' @importFrom ggtern ggtern aes geom_mask\n#'   scale_L_continuous scale_R_continuous scale_T_continuous\n#'   geom_Lline geom_Tline geom_Rline theme_classic\n#' @importFrom rlang .data\n#'\n#' @keywords internal\nBasicKey <- function(legend_surface, limits, brklab, show_center, center, lwd) {\n\n  key <-\n    # basic legend\n    ggtern(legend_surface) +\n    layer(\n      geom = 'polygon', stat = 'identity', position = 'identity',\n      mapping = aes(\n        x = .data[['p1']], y = .data[['p2']], z = .data[['p3']],\n        group = .data[['id']], fill = .data[['rgb']], color = .data[['rgb']]\n      ),\n      params = list(lwd = lwd),\n      check.aes = FALSE, check.param = FALSE\n    ) +\n    geom_mask() +\n    # rgb color input\n    scale_color_identity(guide = 'none') +\n    scale_fill_identity(guide = 'none') +\n    # theme\n    theme_classic() +\n    theme(tern.axis.title.L = element_text(hjust = 0.2, vjust = 1, angle = -60),\n          tern.axis.title.R = element_text(hjust = 0.8, vjust = 0.6, angle = 60)) +\n    # grid and labels\n    list(\n      list(\n        scale_L_continuous(\n          limits = limits[,1],\n          breaks = brklab[['breaks']][['p1']],\n          labels = brklab[['labels']][['p1']]\n        ),\n        scale_T_continuous(\n          limits = limits[,2],\n          breaks = brklab[['breaks']][['p2']],\n          labels = brklab[['labels']][['p2']]\n        ),\n        scale_R_continuous(\n          limits = limits[,3],\n          breaks = brklab[['breaks']][['p3']],\n          labels = brklab[['labels']][['p3']]\n        )\n      ),\n      if (show_center) {\n        list(\n          geom_Lline(Lintercept = center[1], color = 'black', alpha = 0.5),\n          geom_Tline(Tintercept = center[2], color = 'black', alpha = 0.5),\n          geom_Rline(Rintercept = center[3], color = 'black', alpha = 0.5)\n        )\n      }\n    )\n\n  return(key)\n\n}\n\n#' Ternary Balance Scheme Legend\n#'\n#' Plot a ternary balance scheme legend.\n#'\n#' @inheritParams ColorMapTricolore\n#' @param label_as \"pct\" for percent-share labels or \"pct_diff\" for\n#'   percent-point-difference from center labels.\n#' @param show_center Should the center be marked on the legend? (logical)\n#' @param limits A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.\n#'\n#' @return A ggtern grob.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' tricolore:::ColorKeyTricolore(center = rep(1/3, 3), breaks = 4,\n#'                               h_ = 80, c_ = 140, l_ = 80,\n#'                               contrast = 0.4, spread = 1,\n#'                               label_as = \"pct\", show_center = FALSE)\n#'\n#' @keywords internal\nColorKeyTricolore <- function (center, breaks, h_, c_, l_, contrast, spread,\n                               label_as, show_center,\n                               limits = matrix(0:1, nrow = 2, ncol = 3)) {\n\n  ### Create and colorize legend surface ###\n\n  # don't allow more than 99^2 different colors/regions in the legend\n  if (breaks > 99) { breaks = 100 }\n\n  # calculate ternary vertex coordinates and\n  # fill color for each sub-triangle\n  C <- TernaryMeshCentroids(breaks)\n  V <- TernaryMeshVertices(C)\n  rgb <- ColorMapTricolore(P = C[,-1], center, breaks = 100, h_, c_, l_,\n                           contrast, spread)[['rgb']]\n\n  legend_surface <- data.frame(V, rgb = rep(rgb, 3),\n                               row.names = NULL, check.rows = FALSE,\n                               check.names = FALSE, stringsAsFactors = FALSE)\n\n  ### Breaks and labels ###\n\n  if (label_as == 'pct' && breaks <= 10) {\n    brklab <- BreaksAndLabels(1, center, breaks)\n  }\n  if (label_as == 'pct' && breaks > 10) {\n    brklab <- BreaksAndLabels(2, center, breaks)\n  }\n  if (label_as == 'pct_diff') {\n    brklab <- BreaksAndLabels(3, center, breaks)\n  }\n\n  ### Plot key ###\n\n  return(BasicKey(legend_surface, limits, brklab, show_center, center, lwd = 1))\n\n}\n\n#' Sextant Scheme Legend\n#'\n#' Plot a sextant scheme legend.\n#'\n#' @inheritParams ColorMapSextant\n#' @param label_as \"pct\" for percent-share labels or \"pct_diff\" for\n#'   percent-point-difference from center labels.\n#' @param show_center Should the center be marked on the legend? (logical)\n#' @param limits A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.\n#'\n#' @return A ggtern grob.\n#'\n#' @examples\n#' # NOTE: only intended for internal use and not part of the API\n#' tricolore:::ColorKeySextant(center = prop.table(runif(3)),\n#'                             values = c('#01A0C6', '#B8B3D8', '#F11D8C',\n#'                                        '#FFB3B3', '#FFFF00', '#B3DCC3'),\n#'                             label_as = 'pct_diff', show_center = TRUE)\n#'\n#' @keywords internal\nColorKeySextant <- function (center, values, label_as, show_center,\n                             limits = matrix(0:1, nrow = 2, ncol = 3)) {\n\n  ### Create and colorize legend surface ###\n\n  # calculate ternary vertex coordinates and\n  # fill color for each sub-triangle\n  V <- TernarySextantVertices(center)\n  rgb <- rep(values, c(5, 4, 5, 4, 5, 4))\n\n  legend_surface <- data.frame(V, rgb = rgb,\n                               row.names = NULL, check.rows = FALSE,\n                               check.names = FALSE, stringsAsFactors = FALSE)\n\n  ### Breaks and labels ###\n\n  if (label_as == 'pct') {\n    brklab <- BreaksAndLabels(2, center)\n  }\n  if (label_as == 'pct_diff') {\n    brklab <- BreaksAndLabels(3, center)\n  }\n\n  ### Plot key ###\n\n  return(BasicKey(legend_surface, limits, brklab, show_center, center, lwd = 0))\n\n}\n\n# User functions ----------------------------------------------------------\n\n#' Ternary Balance Color Scale\n#'\n#' Color-code three-part compositions with a ternary balance color scale and\n#' return a color key.\n#'\n#' @param df Data frame of compositional data.\n#' @param p1 Column name for variable in df giving first proportion\n#'           of ternary composition (string).\n#' @param p2 Column name for variable in df giving second proportion\n#'           of ternary composition (string).\n#' @param p3 Column name for variable in df giving third proportion\n#'           of ternary composition (string).\n#' @param center Ternary coordinates of the color scale center.\n#'               (default = 1/3,1/3,1/3). NA puts center over the compositional\n#'               mean of the data.\n#' @param breaks Number of per-axis breaks in the discrete color scale.\n#'               An integer >1. Values above 99 imply no discretization.\n#' @param hue Primary hue of the first ternary element (0 to 1).\n#' @param chroma Maximum possible chroma of mixed colors (0 to 1).\n#' @param lightness Lightness of mixed colors (0 to 1).\n#' @param contrast Lightness contrast of the color scale (0 to 1).\n#' @param spread The spread of the color scale. Choose values > 1 to focus the\n#'               color scale on the center.\n#' @param legend Should a legend be returned along with the colors? (default=TRUE)\n#' @param show_data Should the data be shown on the legend? (default=TRUE)\n#' @param show_center Should the center be shown on the legend?\n#'   (default=FALSE if center is at c(1/3, 1/3, 1/3), otherwise TRUE)\n#' @param label_as \"pct\" for percent-share labels or \"pct_diff\" for\n#'   percent-point-difference from center labels.\n#'   (default='pct' if center is at c(1/3, 1/3, 1/3), otherwise 'pct_diff')\n#' @param crop Should the legend be cropped to the data? (default=FALSE)\n#' @param input_validation Should the function arguments be validated? (default=TRUE)\n#'\n#' @return\n#' * legend=FALSE: A vector of rgbs hex-codes representing the ternary balance\n#'                 scheme colors.\n#' * legend=TRUE: A list with elements \"rgb\" and \"key\".\n#'\n#' @examples\n#' P <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))\n#' Tricolore(P, 'V1', 'V2', 'V3')\n#'\n#' @importFrom ggplot2 labs layer\n#' @importFrom ggtern aes\n#' @importFrom rlang .data\n#'\n#' @md\n#'\n#' @export\nTricolore <- function (df, p1, p2, p3,\n                       center = rep(1/3, 3),\n                       breaks = ifelse(identical(center, rep(1/3, 3)), 4, Inf),\n                       hue = 0.2, chroma = 0.7, lightness = 0.8,\n                       contrast = 0.4, spread = 1,\n                       legend = TRUE, show_data = TRUE,\n                       show_center = ifelse(identical(center, rep(1/3, 3)),\n                                            FALSE, TRUE),\n                       label_as = ifelse(identical(center, rep(1/3, 3)),\n                                         'pct', 'pct_diff'),\n                       crop = FALSE, input_validation = TRUE) {\n\n  # validation of main input arguments\n  if (input_validation) {\n    ValidateMainArguments(df, p1, p2, p3)\n    ValidateParametersTricolore(\n      list(breaks = breaks, hue = hue, chroma = chroma,\n           lightness = lightness, contrast = contrast,\n           center = center, spread = spread, legend = legend,\n           show_data = show_data, show_center = show_center,\n           label_as = label_as, crop = crop)\n    )\n  }\n\n  # construct 3 column matrix of proportions\n  P <- cbind(df[[p1]], df[[p2]], df[[p3]])\n  # ensure data is closed\n  P <- prop.table(P, 1)\n\n  # center color-scale over data's centre if center==NA\n  if ( is.na(center[1]) ) { center = Centre(P) }\n\n  # derive the color mixture\n  # the magic numbers rescale the [0,1] color-specification to the\n  # cylindrical-coordinates format required by ColorMapTricolore()\n  mixture <- ColorMapTricolore(P, center, breaks,\n                               hue*360, chroma*200, lightness*100,\n                               contrast, spread)\n\n  # if specified, return a legend along with the srgb color mixtures...\n  if (legend) {\n\n    # crop legend to to data range if crop==TRUE\n    if (crop) {\n      limits <- TernaryLimits(P, na.rm = TRUE)\n      # else use full range\n    } else {\n      limits <- matrix(0:1, nrow = 2, ncol = 3)\n    }\n\n    key <-\n      ColorKeyTricolore(center, breaks, hue*360, chroma*200, lightness*100,\n                        contrast, spread, label_as, show_center, limits) +\n      list(\n        # labels take names from input variables\n        labs(x = p1, y = p2, z = p3),\n        if (show_data) {\n          layer(\n            geom = 'point', stat = 'identity', position = 'identity',\n            mapping = aes(x = .data[['p1']], y = .data[['p2']], z = .data[['p3']]),\n            params = list(color = 'black', shape = 16, size = 0.5, alpha = 0.5),\n            data = mixture,\n            check.aes = FALSE, check.param = FALSE\n          )\n        }\n      )\n\n    result <- list(rgb = mixture[['rgb']], key = key)\n    # ... else just return a vector of hexsrgb codes of the mixed colors\n  } else {\n    result <- mixture[['rgb']]\n  }\n\n  return(result)\n}\n\n\n#' Ternary Sextant Color Scale\n#'\n#' Color-code three-part compositions with a ternary sextant color scale and\n#' return a color key.\n#'\n#' @param df Data frame of compositional data.\n#' @param p1 Column name for variable in df giving first proportion\n#'           of ternary composition (string).\n#' @param p2 Column name for variable in df giving second proportion\n#'           of ternary composition (string).\n#' @param p3 Column name for variable in df giving third proportion\n#'           of ternary composition (string).\n#' @param center Ternary coordinates of the color scale center.\n#'               (default = 1/3,1/3,1/3). NA puts center over the compositional\n#'               mean of the data.\n#' @param values 6 element character vector of rgb-codes.\n#' @param legend Should a legend be returned along with the colors? (default=TRUE)\n#' @param show_data Should the data be shown on the legend? (default=TRUE)\n#' @param show_center Should the center be shown on the legend?\n#' (default=FALSE if center is at c(1/3, 1/3, 1/3), otherwise TRUE)\n#' @param label_as \"pct\" for percent-share labels or \"pct_diff\" for\n#'   percent-point-difference from center labels.\n#'   (default='pct' if center is at c(1/3, 1/3, 1/3), otherwise 'pct_diff')\n#' @param crop Should the legend be cropped to the data? (default=FALSE)\n#' @param input_validation Should the function arguments be validated? (default=TRUE)\n#'\n#' @return\n#' * legend=FALSE: A vector of rgbs hex-codes representing the ternary balance\n#'                 scheme colors.\n#' * legend=TRUE: A list with elements \"rgb\" and \"key\".\n#'\n#' @examples\n#' P <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))\n#' TricoloreSextant(P, 'V1', 'V2', 'V3')\n#'\n#' @importFrom ggplot2 labs layer\n#' @importFrom ggtern aes\n#' @importFrom rlang .data\n#'\n#' @md\n#'\n#' @export\nTricoloreSextant <- function (df, p1, p2, p3,\n                              center = rep(1/3, 3),\n                              values = c(\"#FFFF00\", \"#B3DCC3\", \"#01A0C6\",\n                                         \"#B8B3D8\", \"#F11D8C\", \"#FFB3B3\"),\n                              legend = TRUE, show_data = TRUE, show_center = TRUE,\n                              label_as = ifelse(identical(center, rep(1/3, 3)),\n                                                'pct', 'pct_diff'),\n                              crop = FALSE, input_validation = TRUE) {\n\n  # validation of main input arguments\n  if (input_validation) {\n    ValidateMainArguments(df, p1, p2, p3)\n    ValidateParametersTricoloreSextant(\n      list(values = values,\n           center = center,\n           legend = legend,\n           show_data = show_data,\n           show_center = show_center,\n           label_as = label_as,\n           crop = crop)\n    )\n  }\n\n  # construct 3 column matrix of proportions\n  P <- cbind(df[[p1]], df[[p2]], df[[p3]])\n  # ensure data is closed\n  P <- prop.table(P, 1)\n\n  # center color-scale over data's centre if center==NA\n  if ( is.na(center[1]) ) { center = Centre(P) }\n\n  # derive the color mixture\n  mixture <- ColorMapSextant(P, center, values)\n\n  # if specified, return a legend along with the srgb color mixtures...\n  if (legend) {\n\n    # crop legend to to data range if crop==TRUE\n    if (crop) {\n      limits <- TernaryLimits(P, na.rm = TRUE)\n      # else use full range\n    } else {\n      limits <- matrix(0:1, nrow = 2, ncol = 3)\n    }\n\n    key <-\n      ColorKeySextant(center, values, label_as, show_center, limits) +\n      list(\n        # labels take names from input variables\n        labs(x = p1, y = p2, z = p3),\n        if (show_data) {\n          layer(\n            geom = 'point', stat = 'identity', position = 'identity',\n            mapping = aes(x = .data[['p1']], y = .data[['p2']], z = .data[['p3']]),\n            params = list(color = 'black', shape = 16, size = 0.5, alpha = 0.5),\n            data = mixture,\n            check.aes = FALSE, check.param = FALSE\n          )\n        }\n      )\n\n    result <- list(rgb = mixture[['rgb']], key = key)\n    # ... else just return a vector of hexsrgb codes of the mixed colors\n  } else {\n    result <- mixture[['rgb']]\n  }\n\n  return(result)\n\n}\n\n#' Interactive Tricolore Demonstration\n#'\n#' An interactive demonstration of the tricolore color scale inspired by the\n#' colorbrewer2.org application. Helps in picking the right color scale for your\n#' data.\n#'\n#' @return Opens a shiny app session.\n#'\n#' @export\nDemoTricolore <- function () {\n  app_dir <- system.file('shiny', package = 'tricolore')\n  if (app_dir == '') {\n    stop(\"Could not find example directory. Try re-installing 'tricolore'.\",\n         call. = FALSE)\n  }\n  shiny::runApp(app_dir, display.mode = 'normal')\n}\n\n# Data --------------------------------------------------------------------\n\n#' Flat Map of European Continent\n#'\n#' A ggplot object rendering a flat background map of the European continent.\n#'\n#' @source\n#'   Derived from geodata provided by the Natural Earth project.\n#'   \\url{https://www.naturalearthdata.com/}\n'euro_basemap'\n\n#' NUTS-2 Level Geodata and Compositional Data for Europe\n#'\n#' A simple-features dataframe containing the NUTS-2 level polygons of European\n#' regions along with regional compositional data on education and labor-force.\n#'\n#' @format\n#'   A data frame with 312 rows and 9 variables:\n#'   \\describe{\n#'     \\item{id}{NUTS-2 code.}\n#'     \\item{name}{Name of NUTS-2 region.}\n#'     \\item{ed_0to2}{Share of population with highest attained education \"lower secondary or less\".}\n#'     \\item{ed_3to4}{Share of population with highest attained education \"upper secondary\".}\n#'     \\item{ed_5to8}{Share of population with highest attained education \"tertiary\".}\n#'     \\item{lf_pri}{Share of labor-force in primary sector.}\n#'     \\item{lf_sec}{Share of labor-force in secondary sector.}\n#'     \\item{lf_ter}{Share of labor-force in tertiary sector.}\n#'     \\item{geometry}{Polygon outlines for regions in sf package format.}\n#'   }\n#'\n#' @details\n#'   Variables starting with \"ed\" refer to the relative share of population ages\n#'   25 to 64 by educational attainment in the European NUTS-2 regions 2016.\n#'\n#'   Variables starting with \"lf\" refer to the relative share of workers by\n#'   labor-force sector in the European NUTS-2 regions 2016. The original NACE\n#'   (rev. 2) codes have been recoded into the three sectors \"primary\" (A),\n#'   \"secondary\" (B-E & F) and \"tertiary\" (all other NACE codes).\n#'\n#' @source\n#'   Derived from Eurostats European Geodata.\n#'   (c) EuroGeographics for the administrative boundaries.\n#'   \\url{https://gisco-services.ec.europa.eu/distribution/v2/nuts/nuts-2016-files.html}\n#'\n#'   Education data derived from Eurostats table \"edat_lfse_04\".\n#'\n#'   Labor-force data derived from Eurostats table \"lfst_r_lfe2en2\".\n'euro_example'\n"
  },
  {
    "path": "R/zzz.R",
    "content": ".onAttach <- function(...) {\n\n  packageStartupMessage('Please cite tricolore. See citation(\"tricolore\").')\n\n}\n"
  },
  {
    "path": "README.Rmd",
    "content": "---\ntitle: \"tricolore. A flexible color scale for ternary compositions\"\noutput: github_document\n---\n\n```{r echo=FALSE}\nknitr::opts_chunk$set(warning=FALSE,\n                      message=FALSE,\n                      fig.width = 12,\n                      fig.height = 12)\n```\n\nJonas Schöley [![ORCID](https://info.orcid.org/wp-content/uploads/2019/11/orcid_16x16.png)](https://orcid.org/0000-0002-3340-8518) [jschoeley.com](https://www.jschoeley.com/) ·\nIlya Kashnitsky [![ORCID](https://info.orcid.org/wp-content/uploads/2019/11/orcid_16x16.png)](https://orcid.org/0000-0003-1835-8687) [ikashnitsky.phd](https://ikashnitsky.phd/me.html)\n\n[![CRAN_Version](https://www.r-pkg.org/badges/version/tricolore)](https://cran.r-project.org/package=tricolore)\n![GitHub Actions R-CMD-check](https://github.com/jschoeley/tricolore/actions/workflows/R-CMD-check.yaml/badge.svg)\n[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)\n\nWhat is *tricolore*?\n--------------------\n\n`tricolore` is an R library providing a flexible color scale for the visualization of three-part (ternary) compositions. Its main functionality is to color-code any ternary composition as a mixture of three primary colors and to draw a suitable color-key. `tricolore` flexibly adapts to different visualization challenges via\n\n- *discrete* and *continuous* color support,\n- support for unbalanced compositional data via *centering*,\n- support for data with very narrow range via *scaling*,\n- *hue*, *chroma* and *lightness* options.\n\n![](README_files/teaser.png)\n\nGetting Started\n---------------\n\n```{r eval=FALSE}\ninstall.packages('tricolore')\nlibrary(tricolore); DemoTricolore()\n```\n\nThe `Tricolore()` function expects a dataframe of three-part compositions, color-codes the compositions and returns a list with elements `rgb` and `key`. The first list element is a vector of rgb codes for the color-coded compositions, the latter element gives a plot of the color key.\n\nHere's a minimal example using simulated data.\n\n```{r message=FALSE, fig.cap='A ternary color key with the color-coded compositional data visible as points.'}\nlibrary(tricolore)\n\n# simulate 243 ternary compositions\nP <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))\n# color-code each composition and return a corresponding color key\ncolors_and_legend <- Tricolore(P, 'V1', 'V2', 'V3')\n# the color-coded compositions\nhead(colors_and_legend$rgb)\ncolors_and_legend$key\n```\n\nYou can familiarize yourself with the various options of `tricolore` by running `DemoTricolore()`.\n\nTernary choropleth maps\n-----------------------\n\nHere I demonstrate how to create a choropleth map of the regional distribution of education attainment in Europe 2016 using `ggplot2`.\n\nThe data set `euro_example` contains the administrative boundaries for the European NUTS-2 regions in the column `geometry`. This data can be used to plot a choropleth map of Europe using the `sf` package. Each region is represented by a single row. The name of a region is given by the variable `name` while the respective [NUTS-2](https://en.wikipedia.org/wiki/Nomenclature_of_Territorial_Units_for_Statistics) geocode is given by the variable `id`. For each region some compositional statistics are available: Variables starting with `ed` refer to the relative share of population ages 25 to 64 by educational attainment in 2016 and variables starting with `lf` refer to the relative share of workers by labor-force sector in the European NUTS-2 regions 2016.\n\n**1. Using the `Tricolore()` function, color-code each educational composition in the `euro_example` data set and add the resulting vector of hex-srgb colors as a new variable to the dataframe. Store the color key separately.**\n\n```{r}\n# color-code the data set and generate a color-key\ntric_educ <- Tricolore(euro_example,\n                       p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8')\n```\n\n`tric` contains both a vector of color-coded compositions (`tric$rgb`) and the corresponding color key (`tric$key`). We add the vector of colors to the map-data.\n\n```{r}\n# add the vector of colors to the `euro_example` data\neuro_example$educ_rgb <- tric_educ$rgb\n```\n\n**2. Using `ggplot2` and the joined color-coded education data and geodata, plot a ternary choropleth map of education attainment in the European regions. Add the color key to the map.**\n\nThe secret ingredient is `scale_fill_identity()` to make sure that each region is colored according to the value in the `educ_rgb` variable of `euro_example`.\n\n```{r}\nlibrary(ggplot2)\n\nplot_educ <-\n  # using data sf data `euro_example`...\n  ggplot(euro_example) +\n  # ...draw a choropleth map\n  geom_sf(aes(fill = educ_rgb, geometry = geometry), size = 0.1) +\n  # ...and color each region according to the color-code\n  # in the variable `educ_rgb`\n  scale_fill_identity()\n\nplot_educ\n```\n\nUsing `annotation_custom()` and `ggplotGrob` we can add the color key produced by `Tricolore()` to the map. Internally, the color key is produced with the [`ggtern`](http://www.ggtern.com/) package. In order for it to render correctly we need to load `ggtern` *after* loading `ggplot2`. Don't worry, the `ggplot2` functions still work.\n\n```{r}\nlibrary(ggtern)\nplot_educ +\n  annotation_custom(\n    ggplotGrob(tric_educ$key),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  )\n```\n\nBecause the color key behaves just like a `ggplot2` plot we can change it to our liking.\n\n```{r}\nplot_educ <-\n  plot_educ +\n  annotation_custom(\n    ggplotGrob(\n      tric_educ$key +\n        labs(L = '0-2', T = '3-4', R = '5-8')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  )\nplot_educ\n```\n\nSome final touches...\n\n```{r}\nplot_educ +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in educational attainment',\n       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')\n```\n\nContinuous vs. discrete colors\n------------------------------\n\nBy default `tricolore` uses a discrete colors scale with 16 colors. This can be changed via the `breaks` parameter. A value of `Inf` gives a continuous color scale...\n\n```{r}\n# color-code the data set and generate a color-key\ntric_educ_disc <- Tricolore(euro_example,\n                            p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',\n                            breaks = Inf)\neuro_example$educ_rgb_disc <- tric_educ_disc$rgb\n\nggplot(euro_example) +\n  geom_sf(aes(fill = educ_rgb_disc, geometry = geometry), size = 0.1) +\n  scale_fill_identity() +\n  annotation_custom(\n    ggplotGrob(\n      tric_educ_disc$key +\n        labs(L = '0-2', T = '3-4', R = '5-8')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  ) +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in educational attainment',\n       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')\n```\n\n...and a `breaks = 2` gives a discrete color scale with $2^2=4$ colors, highlighting the regions with an absolute majority of any part of the composition.\n\n```{r}\n# color-code the data set and generate a color-key\ntric_educ_disc <- Tricolore(euro_example,\n                            p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',\n                            breaks = 2)\neuro_example$educ_rgb_disc <- tric_educ_disc$rgb\n\nggplot(euro_example) +\n  geom_sf(aes(fill = educ_rgb_disc, geometry = geometry), size = 0.1) +\n  scale_fill_identity() +\n  annotation_custom(\n    ggplotGrob(\n      tric_educ_disc$key +\n        labs(L = '0-2', T = '3-4', R = '5-8')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  ) +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in educational attainment',\n       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')\n```\n\nTernary centering\n-----------------\n\nWhile the ternary balance scheme allows for dense yet clear visualizations of *well spread out* ternary compositions the technique is less informative when used with highly *unbalanced data*. The map below shows the regional labor force composition in Europe as of 2016 in nearly monochromatic colors, the different shades of blue signifying a working population which is concentrated in the tertiary (services) sector. Regions in Turkey and Eastern Europe show a somewhat higher concentration of workers in the primary (production) sector but overall the data shows little variation with regards to the *visual reference point*, i.e. the greypoint marking perfectly balanced proportions.\n\n```{r}\ntric_lf_non_centered <- Tricolore(euro_example, breaks = Inf,\n                                  'lf_pri', 'lf_sec', 'lf_ter')\n\neuro_example$rgb_lf_non_centered <- tric_lf_non_centered$rgb\n\nggplot(euro_example) +\n  geom_sf(aes(fill = rgb_lf_non_centered, geometry = geometry), size = 0.1) +\n  scale_fill_identity() +\n  annotation_custom(\n    ggplotGrob(tric_lf_non_centered$key +\n                 labs(L = '% Primary', T = '% Secondary', R = '% Tertiary')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  ) +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in labor force composition',\n       subtitle = 'Regional distribution of labor force across the three sectors in 2016.')\n\n```\n\nA remedy for analyzing data which shows little variation in relation to some reference point is to *change the point of reference*. The map below yet again shows the European regional labor force composition in 2016 but the color scale has been altered so that its greypoint -- the visual point of reference -- is positioned at the European annual average. Consequently the colors now show direction and magnitude of the deviation from the European average labor force composition. Pink, Green and Blue hues show a higher than average share of workers in the primary, secondary and tertiary sector respectively. The saturation of the colors show the magnitude of that deviation with perfect grey marking a region that has a labor force composition equal to the European average, i.e. the reference point.\n\nCentering the color scale over the labor-force composition of the average European NUTS-2 region shows various patterns of deviations from the average. Metropolitan regions (Hamburg, Stockholm, Paris, Madrid) have a higher than average share of tertiary workers. Large parts of France are quite grey, indicating a labor-force composition close to the average, while Eastern Europe, the south of Spain and Italy have a higher than average share of workers active in the primary sector.\n\n```{r}\ntric_lf_centered <-\n  Tricolore(euro_example,\n            'lf_pri', 'lf_sec', 'lf_ter',\n            center = NA, crop = FALSE)\n\neuro_example$rgb_lf_centered <- tric_lf_centered$rgb\n\nggplot(euro_example) +\n  geom_sf(aes(fill = rgb_lf_centered, geometry = geometry), size = 0.1) +\n  scale_fill_identity() +\n  annotation_custom(\n    ggplotGrob(\n      tric_lf_centered$key +\n        labs(L = '% Primary', T = '% Secondary', R = '% Tertiary')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  ) +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in labor force composition',\n       subtitle = 'Regional distribution of labor force across the three sectors in 2016.')\n```\n\nContributing\n------------\n\nThis software is an academic project. We welcome any issues and pull requests.\n\nPlease report any bugs you find by submitting an issue on github.com/jschoeley/tricolore/issues.\n\nIf you wish to contribute, please submit a pull request following the guidelines stated in [CONTRIBUTING.md](https://github.com/jschoeley/tricolore/blob/devel/CONTRIBUTING.md).\n"
  },
  {
    "path": "README.md",
    "content": "<img src=\"inst/figures/tricolore.png\" align=\"right\" width=\"150\" height=\"174\" />tricolore. A flexible color scale for ternary compositions\n================\n\nJonas Schöley\n[![ORCID](https://info.orcid.org/wp-content/uploads/2019/11/orcid_16x16.png)](https://orcid.org/0000-0002-3340-8518)\n[jschoeley.com](https://www.jschoeley.com/) · Ilya Kashnitsky\n[![ORCID](https://info.orcid.org/wp-content/uploads/2019/11/orcid_16x16.png)](https://orcid.org/0000-0003-1835-8687)\n[ikashnitsky.phd](https://ikashnitsky.phd/me.html)\n\n[![CRAN_Version](https://www.r-pkg.org/badges/version/tricolore)](https://cran.r-project.org/package=tricolore)\n![GitHub Actions\nR-CMD-check](https://github.com/jschoeley/tricolore/actions/workflows/R-CMD-check.yaml/badge.svg)\n[![License: GPL\nv3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)\n\n## What is *tricolore*?\n\n`tricolore` is an R library providing a flexible color scale for the\nvisualization of three-part (ternary) compositions. Its main\nfunctionality is to color-code any ternary composition as a mixture of\nthree primary colors and to draw a suitable color-key. `tricolore`\nflexibly adapts to different visualization challenges via\n\n- *discrete* and *continuous* color support,\n- support for unbalanced compositional data via *centering*,\n- support for data with very narrow range via *scaling*,\n- *hue*, *chroma* and *lightness* options.\n\n![](README_files/teaser.png)\n\n## Getting Started\n\n``` r\ninstall.packages('tricolore')\nlibrary(tricolore); DemoTricolore()\n```\n\nThe `Tricolore()` function expects a dataframe of three-part\ncompositions, color-codes the compositions and returns a list with\nelements `rgb` and `key`. The first list element is a vector of rgb\ncodes for the color-coded compositions, the latter element gives a plot\nof the color key.\n\nHere’s a minimal example using simulated data.\n\n``` r\nlibrary(tricolore)\n\n# simulate 243 ternary compositions\nP <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))\n# color-code each composition and return a corresponding color key\ncolors_and_legend <- Tricolore(P, 'V1', 'V2', 'V3')\n# the color-coded compositions\nhead(colors_and_legend$rgb)\n```\n\n    ## [1] \"#727272\" \"#4AA0BB\" \"#6E8E72\" \"#BC8C67\" \"#37A789\" \"#A48AC6\"\n\n``` r\ncolors_and_legend$key\n```\n\n<figure>\n<img src=\"README_files/figure-gfm/unnamed-chunk-3-1.png\"\nalt=\"A ternary color key with the color-coded compositional data visible as points.\" />\n<figcaption aria-hidden=\"true\">A ternary color key with the color-coded\ncompositional data visible as points.</figcaption>\n</figure>\n\nYou can familiarize yourself with the various options of `tricolore` by\nrunning `DemoTricolore()`.\n\n## Ternary choropleth maps\n\nHere I demonstrate how to create a choropleth map of the regional\ndistribution of education attainment in Europe 2016 using `ggplot2`.\n\nThe data set `euro_example` contains the administrative boundaries for\nthe European NUTS-2 regions in the column `geometry`. This data can be\nused to plot a choropleth map of Europe using the `sf` package. Each\nregion is represented by a single row. The name of a region is given by\nthe variable `name` while the respective\n[NUTS-2](https://en.wikipedia.org/wiki/Nomenclature_of_Territorial_Units_for_Statistics)\ngeocode is given by the variable `id`. For each region some\ncompositional statistics are available: Variables starting with `ed`\nrefer to the relative share of population ages 25 to 64 by educational\nattainment in 2016 and variables starting with `lf` refer to the\nrelative share of workers by labor-force sector in the European NUTS-2\nregions 2016.\n\n**1. Using the `Tricolore()` function, color-code each educational\ncomposition in the `euro_example` data set and add the resulting vector\nof hex-srgb colors as a new variable to the dataframe. Store the color\nkey separately.**\n\n``` r\n# color-code the data set and generate a color-key\ntric_educ <- Tricolore(euro_example,\n                       p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8')\n```\n\n`tric` contains both a vector of color-coded compositions (`tric$rgb`)\nand the corresponding color key (`tric$key`). We add the vector of\ncolors to the map-data.\n\n``` r\n# add the vector of colors to the `euro_example` data\neuro_example$educ_rgb <- tric_educ$rgb\n```\n\n**2. Using `ggplot2` and the joined color-coded education data and\ngeodata, plot a ternary choropleth map of education attainment in the\nEuropean regions. Add the color key to the map.**\n\nThe secret ingredient is `scale_fill_identity()` to make sure that each\nregion is colored according to the value in the `educ_rgb` variable of\n`euro_example`.\n\n``` r\nlibrary(ggplot2)\n\nplot_educ <-\n  # using data sf data `euro_example`...\n  ggplot(euro_example) +\n  # ...draw a choropleth map\n  geom_sf(aes(fill = educ_rgb, geometry = geometry), size = 0.1) +\n  # ...and color each region according to the color-code\n  # in the variable `educ_rgb`\n  scale_fill_identity()\n\nplot_educ\n```\n\n![](README_files/figure-gfm/unnamed-chunk-6-1.png)<!-- -->\n\nUsing `annotation_custom()` and `ggplotGrob` we can add the color key\nproduced by `Tricolore()` to the map. Internally, the color key is\nproduced with the [`ggtern`](http://www.ggtern.com/) package. In order\nfor it to render correctly we need to load `ggtern` *after* loading\n`ggplot2`. Don’t worry, the `ggplot2` functions still work.\n\n``` r\nlibrary(ggtern)\nplot_educ +\n  annotation_custom(\n    ggplotGrob(tric_educ$key),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  )\n```\n\n![](README_files/figure-gfm/unnamed-chunk-7-1.png)<!-- -->\n\nBecause the color key behaves just like a `ggplot2` plot we can change\nit to our liking.\n\n``` r\nplot_educ <-\n  plot_educ +\n  annotation_custom(\n    ggplotGrob(\n      tric_educ$key +\n        labs(L = '0-2', T = '3-4', R = '5-8')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  )\nplot_educ\n```\n\n![](README_files/figure-gfm/unnamed-chunk-8-1.png)<!-- -->\n\nSome final touches…\n\n``` r\nplot_educ +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in educational attainment',\n       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')\n```\n\n![](README_files/figure-gfm/unnamed-chunk-9-1.png)<!-- -->\n\n## Continuous vs. discrete colors\n\nBy default `tricolore` uses a discrete colors scale with 16 colors. This\ncan be changed via the `breaks` parameter. A value of `Inf` gives a\ncontinuous color scale…\n\n``` r\n# color-code the data set and generate a color-key\ntric_educ_disc <- Tricolore(euro_example,\n                            p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',\n                            breaks = Inf)\neuro_example$educ_rgb_disc <- tric_educ_disc$rgb\n\nggplot(euro_example) +\n  geom_sf(aes(fill = educ_rgb_disc, geometry = geometry), size = 0.1) +\n  scale_fill_identity() +\n  annotation_custom(\n    ggplotGrob(\n      tric_educ_disc$key +\n        labs(L = '0-2', T = '3-4', R = '5-8')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  ) +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in educational attainment',\n       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')\n```\n\n![](README_files/figure-gfm/unnamed-chunk-10-1.png)<!-- -->\n\n…and a `breaks = 2` gives a discrete color scale with $2^2=4$ colors,\nhighlighting the regions with an absolute majority of any part of the\ncomposition.\n\n``` r\n# color-code the data set and generate a color-key\ntric_educ_disc <- Tricolore(euro_example,\n                            p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',\n                            breaks = 2)\neuro_example$educ_rgb_disc <- tric_educ_disc$rgb\n\nggplot(euro_example) +\n  geom_sf(aes(fill = educ_rgb_disc, geometry = geometry), size = 0.1) +\n  scale_fill_identity() +\n  annotation_custom(\n    ggplotGrob(\n      tric_educ_disc$key +\n        labs(L = '0-2', T = '3-4', R = '5-8')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  ) +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in educational attainment',\n       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')\n```\n\n![](README_files/figure-gfm/unnamed-chunk-11-1.png)<!-- -->\n\n## Ternary centering\n\nWhile the ternary balance scheme allows for dense yet clear\nvisualizations of *well spread out* ternary compositions the technique\nis less informative when used with highly *unbalanced data*. The map\nbelow shows the regional labor force composition in Europe as of 2016 in\nnearly monochromatic colors, the different shades of blue signifying a\nworking population which is concentrated in the tertiary (services)\nsector. Regions in Turkey and Eastern Europe show a somewhat higher\nconcentration of workers in the primary (production) sector but overall\nthe data shows little variation with regards to the *visual reference\npoint*, i.e. the greypoint marking perfectly balanced proportions.\n\n``` r\ntric_lf_non_centered <- Tricolore(euro_example, breaks = Inf,\n                                  'lf_pri', 'lf_sec', 'lf_ter')\n\neuro_example$rgb_lf_non_centered <- tric_lf_non_centered$rgb\n\nggplot(euro_example) +\n  geom_sf(aes(fill = rgb_lf_non_centered, geometry = geometry), size = 0.1) +\n  scale_fill_identity() +\n  annotation_custom(\n    ggplotGrob(tric_lf_non_centered$key +\n                 labs(L = '% Primary', T = '% Secondary', R = '% Tertiary')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  ) +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in labor force composition',\n       subtitle = 'Regional distribution of labor force across the three sectors in 2016.')\n```\n\n![](README_files/figure-gfm/unnamed-chunk-12-1.png)<!-- -->\n\nA remedy for analyzing data which shows little variation in relation to\nsome reference point is to *change the point of reference*. The map\nbelow yet again shows the European regional labor force composition in\n2016 but the color scale has been altered so that its greypoint – the\nvisual point of reference – is positioned at the European annual\naverage. Consequently the colors now show direction and magnitude of the\ndeviation from the European average labor force composition. Pink, Green\nand Blue hues show a higher than average share of workers in the\nprimary, secondary and tertiary sector respectively. The saturation of\nthe colors show the magnitude of that deviation with perfect grey\nmarking a region that has a labor force composition equal to the\nEuropean average, i.e. the reference point.\n\nCentering the color scale over the labor-force composition of the\naverage European NUTS-2 region shows various patterns of deviations from\nthe average. Metropolitan regions (Hamburg, Stockholm, Paris, Madrid)\nhave a higher than average share of tertiary workers. Large parts of\nFrance are quite grey, indicating a labor-force composition close to the\naverage, while Eastern Europe, the south of Spain and Italy have a\nhigher than average share of workers active in the primary sector.\n\n``` r\ntric_lf_centered <-\n  Tricolore(euro_example,\n            'lf_pri', 'lf_sec', 'lf_ter',\n            center = NA, crop = FALSE)\n\neuro_example$rgb_lf_centered <- tric_lf_centered$rgb\n\nggplot(euro_example) +\n  geom_sf(aes(fill = rgb_lf_centered, geometry = geometry), size = 0.1) +\n  scale_fill_identity() +\n  annotation_custom(\n    ggplotGrob(\n      tric_lf_centered$key +\n        labs(L = '% Primary', T = '% Secondary', R = '% Tertiary')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  ) +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(title = 'European inequalities in labor force composition',\n       subtitle = 'Regional distribution of labor force across the three sectors in 2016.')\n```\n\n![](README_files/figure-gfm/unnamed-chunk-13-1.png)<!-- -->\n\n## Contributing\n\nThis software is an academic project. We welcome any issues and pull\nrequests.\n\nPlease report any bugs you find by submitting an issue on\ngithub.com/jschoeley/tricolore/issues.\n\nIf you wish to contribute, please submit a pull request following the\nguidelines stated in\n[CONTRIBUTING.md](https://github.com/jschoeley/tricolore/blob/devel/CONTRIBUTING.md).\n"
  },
  {
    "path": "cran-comments.md",
    "content": "This submission fixes CRAN check ERRORs which arose due to the 4.0.0 update of the ggtern import and were ultimately related to the ggplot 4.0.0 version update.\n\n## Test environments\n\n* Linux Mint 21.3, R 4.5.2\n* macOS 15.7.2, R 4.5.2\n* Microsoft Windows Server 2025 10.0.26100, R 4.5.2\n* Ubuntu 24.04.3, R devel\n* Ubuntu 24.04.3, R 4.5.2\n* Ubuntu 24.04.3, R 4.4.3 \n\n## R CMD check results\n\n> 0 errors ✔ | 0 warnings ✔ | 0 notes ✔\n\n## Test results\n\n> [ FAIL 0 | WARN 0 | SKIP 0 | PASS 39 ]\n\n## CRAN maintainer comments\n\n- FIXED invalid URLs\n\n> Found the following (possibly) invalid URLs:\n> https://ec.europa.eu/eurostat/web/gisco/geodata/reference-data/administrative-units-statistical-units/\n> \n> Please fix and resubmit.\n> \n> Best,\n> Uwe Ligges\n"
  },
  {
    "path": "data-raw/euro_basemap.R",
    "content": "#'---\n#' title: A flat and simplified map of Europe\n#' author: Jonas Schöley\n#' date: 2018-08-28\n#'---\n\nlibrary(tidyverse)\nlibrary(sf)\nlibrary(rnaturalearth)\n\neura_sf <-\n  # download geospatial data for European, Asian and African countries\n  ne_countries(continent = c('europe', 'asia', 'africa'), returnclass = 'sf',\n               scale = 50) %>%\n  # project to crs 3035\n  st_transform(crs = 3035) %>%\n  # merge into single polygon\n  st_union(by_feature = FALSE) %>%\n  st_crop(xmin = 25e5, xmax = 75e5, ymin = 13.5e5, ymax = 54.5e5)\n\n# draw a basemap of Europe\neuro_basemap <-\n  ggplot(eura_sf) +\n  geom_sf(color = NA, fill = 'grey90') +\n  coord_sf(expand = FALSE, datum = NA) +\n  theme_void() +\n  theme(panel.border = element_rect(fill = NA, color = 'grey90', linewidth = 1))\n\nsave(euro_basemap, file = './data-raw/euro_basemap.RData', compress = 'xz')\n"
  },
  {
    "path": "data-raw/euro_example.R",
    "content": "#'---\n#' title: Geodata for European NUTS-2 regions with added variables\n#' author: Jonas Schöley\n#' date: 2019-07-19\n#'---\n\n# Init --------------------------------------------------------------------\n\nlibrary(tidyverse)\nlibrary(stringi)\nlibrary(sf)\nlibrary(rmapshaper)\nlibrary(eurostat)\n\n# European NUTS-2 geodata -------------------------------------------------\n\n# download geodata on nuts-2 regions\neuro_geo_nuts2 <-\n  get_eurostat_geospatial(output_class = 'sf',\n                          resolution = '60', nuts_level = 2, year = 2016) %>%\n  # exclude some regions which don't report\n  # the statistics we're interested in\n  filter(!(str_detect(geo, '^AL') | str_detect(geo, '^LI') | geo == 'FI20')) %>%\n  # project to crs 3035\n  st_transform(crs = 3035) %>%\n  # pseudo-buffer regions to avoid self-intersection errors\n  st_buffer(0) %>%\n  # crop to Europe\n  st_crop(xmin = 25e5, xmax = 75e5, ymin = 13.5e5, ymax = 54.5e5) %>%\n  # simplify to save space\n  ms_simplify(keep = 0.05, keep_shapes = TRUE) %>%\n  # transliterate non-ASCII characters in region names\n  # (so that CRAN-check stops complaining)\n  mutate(\n    name = stri_trans_general(NUTS_NAME, id = 'any-latin; latin-ascii')\n  ) %>%\n  # select nuts id, region name and geometry columns\n  select(id, name, geometry)\n\n# Download data on European educational composition -----------------------\n\n# download data on education composition by NUTS-2 level for Europe\neduc <- get_eurostat('edat_lfse_04')\n\n# select data for 2016 and calculate shares\neuro_education <-\n  educ %>%\n  mutate(year = lubridate::year(time),\n         id = as.character(geo)) %>%\n  # year 2016, total population, nuts 2 levels\n  filter(year == 2016,\n         str_length(geo) == 4,\n         isced11 %in% c('ED0-2', 'ED3_4', 'ED5-8'),\n         sex == 'T') %>%\n  mutate(values = values/100) %>%\n  spread(isced11, values) %>%\n  select(id, ed_0to2 = `ED0-2`, ed_3to4 = `ED3_4`, ed_5to8 = `ED5-8`) %>%\n  drop_na()\n\n# Download data on European labor-force composition -----------------------\n\n# download data on labor-force composition by NUTS-2 level for Europe\nlf <- get_eurostat(\"lfst_r_lfe2en2\")\n\n# select data for 2016, recode to ternary sectors and calculate shares\neuro_sectors <-\n  lf %>%\n  # recode time as year and geo as character\n  mutate(\n    year = as.integer(lubridate::year(time)),\n    geo = as.character(geo)\n  ) %>%\n  # subset to total age, year 2016 and NUTS-2 regions\n  filter(\n    age == 'Y_GE15',\n    str_length(geo) == 4,\n    year == 2016\n  ) %>%\n  # if a sector wasn't reported, assume no one worked there\n  # (this is motivated by the \"missing\" agricultural workers in innner london)\n  complete(nace_r2, geo, year, fill = list(values = 0)) %>%\n  # recode into three sectors\n  mutate(\n    sector = recode(as.character(nace_r2),\n                    `A` = 'primary',\n                    `B-E` = 'secondary',\n                    `F` = 'secondary'),\n    sector = ifelse(!sector %in% c('primary', 'secondary', 'TOTAL'),\n                    'tertiary',\n                    sector)\n  ) %>%\n  group_by(year, geo, sector) %>%\n  summarise(N = sum(values, na.rm = TRUE)) %>%\n  ungroup() %>%\n  # calculate shares on total\n  spread(sector, N) %>%\n  mutate_at(vars(primary, secondary, tertiary), .funs = ~ ./TOTAL) %>%\n  # simplify\n  select(id = geo, lf_pri = primary, lf_sec = secondary, lf_ter = tertiary) %>%\n  drop_na()\n\n# Join compositional data with geodata ------------------------------------\n\neuro_example <-\n  euro_geo_nuts2 %>%\n  left_join(euro_education, 'id') %>%\n  left_join(euro_sectors, 'id') %>%\n  arrange(id)\n\nsave(\n  euro_example,\n  file = './data-raw/euro_example.RData',\n  compress = 'xz',\n  version = 2\n)\n\n# Test --------------------------------------------------------------------\n\n# library(leaflet)\n# foo <- tricolore::Tricolore(euro_example,\n#                             p1 = 'lf_pri', p2 = 'lf_sec', p3 = 'lf_ter',\n#                             center = NA, hue = 0.2)\n# euro_example %>%\n#   st_transform(crs = 4326) %>%\n#   leaflet() %>%\n#   addProviderTiles(providers$Esri.WorldTerrain) %>%\n#   addPolygons(color = str_sub(foo$rgb, 1, 7),\n#               weight = 1, smoothFactor = 0.1,\n#               fillColor = str_sub(foo$rgb, 1, 7),\n#               fillOpacity = 1,\n#               popup =\n#                 paste0(\n#                   euro_example$id, euro_example$name, '</br>',\n#                   'Primary: ',\n#                   formatC(euro_example$lf_pri*100,\n#                           digits = 1, format = 'f'), '%</br>',\n#                   ' Secondary: ',\n#                   formatC(euro_example$lf_sec*100,\n#                           digits = 1, format = 'f'), '%</br>',\n#                   ' Tertiary: ',\n#                   formatC(euro_example$lf_ter*100,\n#                           digits = 1, format = 'f'), '%</br>'\n#                 )\n#   )\n# foo <- tricolore::Tricolore(euro_example,\n#                             p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8', hue = 0.2)\n# euro_example %>%\n#   st_transform(crs = 4326) %>%\n#   leaflet() %>%\n#   addProviderTiles(providers$Esri.WorldTerrain) %>%\n#   addPolygons(color = str_sub(foo$rgb, 1, 7),\n#               weight = 1, smoothFactor = 0.1,\n#               fillColor = str_sub(foo$rgb, 1, 7),\n#               fillOpacity = 1,\n#               popup =\n#                 paste0(\n#                   euro_example$id, euro_example$name, '</br>',\n#                   'Primary: ',\n#                   formatC(euro_example$ed_0to2*100,\n#                           digits = 1, format = 'f'), '%</br>',\n#                   ' Secondary: ',\n#                   formatC(euro_example$ed_3to4*100,\n#                           digits = 1, format = 'f'), '%</br>',\n#                   ' Tertiary: ',\n#                   formatC(euro_example$ed_5to8*100,\n#                           digits = 1, format = 'f'), '%</br>'\n#                 )\n#   )\n"
  },
  {
    "path": "inst/CITATION",
    "content": "citHeader('To cite tricolore in publications, please use:')\n\nbibentry(\n  bibtype = 'Article',\n  author = c(person('Jonas', 'Schöley', role = c('aut', 'cre')), person('Ilya', 'Kashnitsky', role = 'aut')),\n  title = 'tricolore. A flexible color scale for ternary compositions',\n  journal = 'CRAN',\n  year = '2025',\n  note = 'Version 1.2.6',\n  url = 'https://cran.r-project.org/package=tricolore',\n  textVersion = 'J. Schöley and I. Kashnitsky (2024). tricolore: A flexible\n  color scale for ternary compositions. Version 1.2.4.  CRAN. URL https://cran.r-project.org/package=tricolore'\n)\n\nbibentry(\n  bibtype = 'Article',\n  author = person('Jonas', 'Schöley'),\n  title = 'The centered ternary balance scheme. A technique to visualize surfaces of unbalanced three-part compositions',\n  journal      = 'Demographic Research',\n  year         = '2021',\n  month        = 'mar',\n  pages        = '443--458',\n  volume       = '44',\n  doi          = '10.4054/DemRes.2021.44.19',\n  textVersion = 'J. Schöley (2021). The centered ternary balance scheme: A technique to visualize surfaces of unbalanced three-part compositions. Demographic Research, Vol. 44, p. 443-458. DOI 10.4054/DemRes.2021.44.19'\n)\n"
  },
  {
    "path": "inst/shiny/app.R",
    "content": "library(shiny)\nlibrary(sf)\nlibrary(ggtern)\nlibrary(tricolore)\n\n# UI ----------------------------------------------------------------------\n\nui <- fluidPage(\n\n  titlePanel(title = 'Tricolore: A flexible color scale for ternary compositions'),\n\n  sidebarLayout(\n\n    # INPUT\n    sidebarPanel(width = 3,\n                 radioButtons(inputId = 'data', label = 'Data', inline = TRUE,\n                              choices = list('Labour force' = 'lf',\n                                             'Education' = 'educ'),\n                              selected = 'educ'),\n                 radioButtons(inputId = 'type', label = 'Type', inline = TRUE,\n                              choices = list('Default' = 'tricolore',\n                                             'Sextant' = 'sextant'),\n                              selected = 'tricolore'),\n                 conditionalPanel(\n                   condition = 'input.type == \"tricolore\"',\n                   sliderInput(inputId = 'hue', label = 'Hue', ticks = FALSE,\n                               min = 0, max = 1, step = 0.1, value = 0.2),\n                   sliderInput(inputId = 'chroma', label = 'Chroma', ticks = FALSE,\n                               min = 0, max = 1, step = 0.1, value = 0.7),\n                   sliderInput(inputId = 'lightness', label = 'Lightness', ticks = FALSE,\n                               min = 0, max = 1, step = 0.1, value = 0.8),\n                   sliderInput(inputId = 'contrast', label = 'Contrast', ticks = FALSE,\n                               min = 0, max = 1, step = 0.1, value = 0.4),\n                   sliderInput(inputId = 'spread', label = 'Spread',\n                               min = 0.5, max = 2, step = 0.1, value = 1, ticks = FALSE),\n                 checkboxInput(inputId = 'discrete', label = 'Discrete', value = FALSE),\n                 conditionalPanel(\n                   condition = 'input.discrete',\n                   sliderInput(inputId = 'breaks', label = 'Breaks', ticks = FALSE,\n                               min = 2, max = 20, step = 1, value = 4)\n                 )),\n                 checkboxInput(inputId = 'center', label = 'Mean centering',\n                               value = FALSE),\n                 checkboxInput(inputId = 'show_center', label = 'Show center',\n                               value = FALSE),\n                 checkboxInput(inputId = 'show_data', label = 'Show data',\n                               value = TRUE),\n                 checkboxInput(inputId = 'crop', label = 'Crop legend',\n                               value = FALSE),\n                 radioButtons(inputId = 'label_as', label = 'Label as',\n                              choices = list('percent-share' = 'pct',\n                                             'pct-pt. difference' = 'pct_diff'),\n                              selected = 'pct'),\n                 verbatimTextOutput(outputId = 'call')\n    ),\n\n    # OUTPUT\n    mainPanel(plotOutput(outputId = 'example'))\n  )\n)\n\n# Server ------------------------------------------------------------------\n\nserver <- function(input, output) {\n\n  output$call <- renderText({\n    paste0(\n      if (input$type == 'tricolore') 'Tricolore(',\n      if (input$type == 'sextant') 'TricoloreSextant(',\n      \"euro_example, \",\n      if (input$data == 'educ') \"p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8'\",\n      if (input$data == 'lf') \"p1 = 'lf_pri', p2 = 'lf_sec', p3 = 'lf_ter'\",\n      ', center = ', ifelse(input$center, 'NA', 'rep(1/3,3)'),\n      if (input$type == 'tricolore') {\n        paste0(\n          ', breaks = ', ifelse(input$discrete, input$breaks, 'Inf'),\n          ', hue = ', input$hue,\n          ', chroma = ', input$chroma,\n          ', lightness = ', input$lightness,\n          ', contrast = ', input$contrast,\n          ', spread = ', input$spread\n        )\n      },\n      ', legend = TRUE',\n      ', show_data = ', input$show_data,\n      ', show_center = ', input$show_center,\n      ', label_as = \"', input$label_as, '\"',\n      ', crop = ', input$crop, ')'\n    )\n  })\n\n  output$example <- renderPlot(res = 120, width = 1000, height = 800, {\n\n    if (input$data == 'educ') {\n      p1 = 'ed_0to2'; p2 = 'ed_3to4'; p3 = 'ed_5to8'\n      title = 'Composition of education levels in European regions 2016\\n'\n    }\n    if (input$data == 'lf') {\n      p1 = 'lf_pri'; p2 = 'lf_sec'; p3 = 'lf_ter'\n      title = 'Labor force composition in European regions 2016\\n'\n    }\n\n    if (input$type == 'tricolore') {\n\n      # mix color, generate legend\n      mixed <- Tricolore(euro_example,\n                         p1 = p1, p2 = p2, p3 = p3,\n                         center = if (input$center) NA else rep(1/3,3),\n                         breaks = ifelse(input$discrete, input$breaks, Inf),\n                         hue = input$hue, chroma = input$chroma,\n                         lightness = input$lightness,\n                         contrast = input$contrast,\n                         spread = input$spread,\n                         show_data = input$show_data,\n                         show_center = input$show_center,\n                         label_as = input$label_as,\n                         crop = input$crop,\n                         legend = TRUE)\n\n    }\n\n    if (input$type == 'sextant') {\n\n      # mix color, generate legend\n      mixed <- TricoloreSextant(euro_example,\n                                p1 = p1, p2 = p2, p3 = p3,\n                                center = if (input$center) NA else rep(1/3,3),\n                                show_data = input$show_data,\n                                show_center = input$show_center,\n                                label_as = input$label_as,\n                                crop = input$crop,\n                                legend = TRUE)\n\n    }\n\n    # customize legend\n    lgnd <- mixed[['key']] +\n      labs(x = 'Primary', y = 'Secondary', z = 'Tertiary',\n           subtitle =\n             paste0(\n               title,\n               ifelse(input$center,\n                      'Colors show deviation from average composition\\n',\n                      'Colors show deviations from balanced composition\\n'),\n               'Data by eurostat'\n             )\n      ) +\n      theme(\n        plot.background = element_blank(),\n        plot.subtitle = element_text(size = 8),\n        panel.background = element_blank(),\n        tern.plot.background = element_blank(),\n        tern.panel.background = element_blank(),\n      )\n\n    # merge data and map\n    euro_example$rgb <- mixed[['rgb']]\n\n    # generate map\n    euro_map <-\n      euro_basemap +\n      geom_sf(aes(fill = rgb, geometry = geometry), color = NA,\n              data = euro_example) +\n      annotation_custom(ggplotGrob(lgnd),\n                        xmin = 54e5, xmax = 74e5,\n                        ymin = 8e5, ymax = 80e5) +\n      scale_fill_identity() +\n      coord_sf(expand = FALSE, datum = NA, default = TRUE)\n\n    print(euro_map)\n  })\n\n}\n\nshinyApp(ui, server)\n"
  },
  {
    "path": "man/BasicKey.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{BasicKey}\n\\alias{BasicKey}\n\\title{Template for Ternary Key}\n\\usage{\nBasicKey(legend_surface, limits, brklab, show_center, center, lwd)\n}\n\\arguments{\n\\item{legend_surface}{A data frame with numeric 'id', 'p1', 'p2', 'p3' and\ncharacter column 'rgb'.}\n\n\\item{limits}{A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.}\n\n\\item{brklab}{Breaks and labels as returned by \\code{\\link{BreaksAndLabels}}.}\n\n\\item{show_center}{Should the center be marked on the legend? (logical)}\n\n\\item{center}{Ternary coordinates of the grey-point.}\n\n\\item{lwd}{A numeric scalar giving the linewidth of the legend surface\npolygons.}\n}\n\\value{\nA ggtern grob.\n}\n\\description{\nReturn various types of breaks and labels for ternary color keys.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/BreaksAndLabels.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{BreaksAndLabels}\n\\alias{BreaksAndLabels}\n\\title{Breaks and Labels for Ternary Color Key}\n\\usage{\nBreaksAndLabels(type, center = NULL, breaks = NULL)\n}\n\\arguments{\n\\item{type}{An integer 1, 2, or 3.}\n\n\\item{center}{Ternary coordinates of the grey-point.}\n\n\\item{breaks}{Number of breaks in the discrete color scale. An integer >1.\nValues above 99 imply no discretization.}\n}\n\\value{\nA list of lists containing breaks and labels for each of the 3\n  ternary axes.\n}\n\\description{\nReturn various types of breaks and labels for ternary color keys.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\ntricolore:::BreaksAndLabels(1, breaks = 3)\ntricolore:::BreaksAndLabels(2)\ntricolore:::BreaksAndLabels(3, center = c(1/3, 1/3, 1/3))\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/Centre.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{Centre}\n\\alias{Centre}\n\\title{Compositional Centre}\n\\usage{\nCentre(P)\n}\n\\arguments{\n\\item{P}{n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.}\n}\n\\value{\nThe centre of P as an m element numeric vector.\n}\n\\description{\nCalculate the centre of a compositional data set.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nP <- prop.table(matrix(runif(300), 100), margin = 1)\ntricolore:::Centre(P)\n\n}\n\\references{\nVon Eynatten, H., Pawlowsky-Glahn, V., & Egozcue, J. J. (2002).\nUnderstanding perturbation on the simplex: A simple method to better\nvisualize and interpret compositional data in ternary diagrams.\nMathematical Geology, 34(3), 249-257.\n\nPawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture\nNotes on Compositional Data Analysis. Retrieved from\nhttps://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/ColorKeySextant.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ColorKeySextant}\n\\alias{ColorKeySextant}\n\\title{Sextant Scheme Legend}\n\\usage{\nColorKeySextant(\n  center,\n  values,\n  label_as,\n  show_center,\n  limits = matrix(0:1, nrow = 2, ncol = 3)\n)\n}\n\\arguments{\n\\item{center}{Ternary coordinates of the sextant meeting point.}\n\n\\item{values}{6 element character vector of rgb-codes.}\n\n\\item{label_as}{\"pct\" for percent-share labels or \"pct_diff\" for\npercent-point-difference from center labels.}\n\n\\item{show_center}{Should the center be marked on the legend? (logical)}\n\n\\item{limits}{A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.}\n}\n\\value{\nA ggtern grob.\n}\n\\description{\nPlot a sextant scheme legend.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\ntricolore:::ColorKeySextant(center = prop.table(runif(3)),\n                            values = c('#01A0C6', '#B8B3D8', '#F11D8C',\n                                       '#FFB3B3', '#FFFF00', '#B3DCC3'),\n                            label_as = 'pct_diff', show_center = TRUE)\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/ColorKeyTricolore.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ColorKeyTricolore}\n\\alias{ColorKeyTricolore}\n\\title{Ternary Balance Scheme Legend}\n\\usage{\nColorKeyTricolore(\n  center,\n  breaks,\n  h_,\n  c_,\n  l_,\n  contrast,\n  spread,\n  label_as,\n  show_center,\n  limits = matrix(0:1, nrow = 2, ncol = 3)\n)\n}\n\\arguments{\n\\item{center}{Ternary coordinates of the grey-point.}\n\n\\item{breaks}{Number of breaks in the discrete color scale. An integer >1.\nValues above 99 imply no discretization.}\n\n\\item{h_}{Primary hue of the first ternary element in angular degrees [0, 360].}\n\n\\item{c_}{Maximum possible chroma of mixed colors [0, 200].}\n\n\\item{l_}{Lightness of mixed colors [0, 100].}\n\n\\item{contrast}{Lightness contrast of the color scale [0, 1).}\n\n\\item{spread}{Spread of the color scale around center > 0.}\n\n\\item{label_as}{\"pct\" for percent-share labels or \"pct_diff\" for\npercent-point-difference from center labels.}\n\n\\item{show_center}{Should the center be marked on the legend? (logical)}\n\n\\item{limits}{A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.}\n}\n\\value{\nA ggtern grob.\n}\n\\description{\nPlot a ternary balance scheme legend.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\ntricolore:::ColorKeyTricolore(center = rep(1/3, 3), breaks = 4,\n                              h_ = 80, c_ = 140, l_ = 80,\n                              contrast = 0.4, spread = 1,\n                              label_as = \"pct\", show_center = FALSE)\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/ColorMapSextant.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ColorMapSextant}\n\\alias{ColorMapSextant}\n\\title{Sextant Encoding of Ternary Composition}\n\\usage{\nColorMapSextant(P, center, values)\n}\n\\arguments{\n\\item{P}{n by 3 matrix of ternary compositions [p1, p2, p3](i) for\ni=1, ..., n.}\n\n\\item{center}{Ternary coordinates of the sextant meeting point.}\n\n\\item{values}{6 element character vector of rgb-codes.}\n}\n\\value{\nAn n row data frame giving, for each row of the input P, the input\nproportions [p1, p2, p3], sextant id (sextant) and the hex-rgb string of the\nmixed colors (rgb).\n}\n\\description{\nReturn the sextant scheme colors for a matrix of ternary compositions.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nP <- prop.table(matrix(runif(9), ncol = 3), 1)\ntricolore:::ColorMapSextant(P, c(1/3, 1/3, 1/3),\n                            c('#01A0C6', '#B8B3D8', '#F11D8C', '#FFB3B3',\n                              '#FFFF00', '#B3DCC3'))\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/ColorMapTricolore.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ColorMapTricolore}\n\\alias{ColorMapTricolore}\n\\title{CIE-Lch Mixture of Ternary Composition}\n\\usage{\nColorMapTricolore(P, center, breaks, h_, c_, l_, contrast, spread)\n}\n\\arguments{\n\\item{P}{n by 3 matrix of ternary compositions [p1, p2, p3](i) for\ni=1, ..., n.}\n\n\\item{center}{Ternary coordinates of the grey-point.}\n\n\\item{breaks}{Number of breaks in the discrete color scale. An integer >1.\nValues above 99 imply no discretization.}\n\n\\item{h_}{Primary hue of the first ternary element in angular degrees [0, 360].}\n\n\\item{c_}{Maximum possible chroma of mixed colors [0, 200].}\n\n\\item{l_}{Lightness of mixed colors [0, 100].}\n\n\\item{contrast}{Lightness contrast of the color scale [0, 1).}\n\n\\item{spread}{Spread of the color scale around center > 0.}\n}\n\\value{\nAn n row data frame giving, for each row of the input P, the input\nproportions [p1, p2, p3], parameters of the color mixture (h, c, l) and the\nhex-rgb string of the mixed colors (rgb).\n}\n\\description{\nReturn the ternary balance scheme colors for a matrix of ternary compositions.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nP <- prop.table(matrix(runif(9), ncol = 3), 1)\ntricolore:::ColorMapTricolore(P, center = rep(1/3, 3), breaks = 4,\n                              h_ = 80, c_ = 140, l_ = 80,\n                              contrast = 0.4, spread = 1)\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/DemoTricolore.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{DemoTricolore}\n\\alias{DemoTricolore}\n\\title{Interactive Tricolore Demonstration}\n\\usage{\nDemoTricolore()\n}\n\\value{\nOpens a shiny app session.\n}\n\\description{\nAn interactive demonstration of the tricolore color scale inspired by the\ncolorbrewer2.org application. Helps in picking the right color scale for your\ndata.\n}\n"
  },
  {
    "path": "man/GeometricMean.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{GeometricMean}\n\\alias{GeometricMean}\n\\title{Geometric Mean}\n\\usage{\nGeometricMean(x, na.rm = TRUE, zero.rm = TRUE)\n}\n\\arguments{\n\\item{x}{Numeric vector.}\n\n\\item{na.rm}{Should NAs be removed? (default=TRUE)}\n\n\\item{zero.rm}{Should zeros be removed? (default=TRUE)}\n}\n\\value{\nThe geometric mean as numeric scalar.\n}\n\\description{\nCalculate the geometric mean for a numeric vector.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\ntricolore:::GeometricMean(0:100)\ntricolore:::GeometricMean(0:100, zero.rm = FALSE)\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/Pertube.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{Pertube}\n\\alias{Pertube}\n\\title{Compositional Pertubation}\n\\usage{\nPertube(P, c = rep(1/3, 3))\n}\n\\arguments{\n\\item{P}{n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.}\n\n\\item{c}{Compositional pertubation vector [c1, ..., cm].}\n}\n\\value{\nn by m matrix of pertubated compositions.\n}\n\\description{\nPertubate a compositional data set by a compositional vector.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nP <- prop.table(matrix(runif(12), 4), margin = 1)\ncP <- tricolore:::Pertube(P, 1/tricolore:::Centre(P))\ntricolore:::Centre(cP)\n\n}\n\\references{\nVon Eynatten, H., Pawlowsky-Glahn, V., & Egozcue, J. J. (2002).\nUnderstanding perturbation on the simplex: A simple method to better\nvisualize and interpret compositional data in ternary diagrams.\nMathematical Geology, 34(3), 249-257.\n\nPawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture\nNotes on Compositional Data Analysis. Retrieved from\nhttps://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/PowerScale.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{PowerScale}\n\\alias{PowerScale}\n\\title{Compositional Powering}\n\\usage{\nPowerScale(P, scale = 1)\n}\n\\arguments{\n\\item{P}{n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.}\n\n\\item{scale}{Power scalar.}\n}\n\\value{\nn by m numeric matrix of powered compositions.\n}\n\\description{\nRaise a compositional data-set to a given power.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nP <- prop.table(matrix(runif(12), 4), margin = 1)\ntricolore:::PowerScale(P, 2)\n\n}\n\\references{\nPawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture\nNotes on Compositional Data Analysis. Retrieved from\nhttps://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/TernaryCenterGrid.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryCenterGrid}\n\\alias{TernaryCenterGrid}\n\\title{Return Ternary Gridlines Centered Around Some Composition}\n\\usage{\nTernaryCenterGrid(center, spacing)\n}\n\\arguments{\n\\item{center}{The center of the grid.\nA vector of ternary coordinates [p1, p2, p3].}\n\n\\item{spacing}{The spacing of the grid in percent-point increments.\nA numeric > 0.}\n}\n\\value{\nA list of lists.\n}\n\\description{\nReturn Ternary Gridlines Centered Around Some Composition\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\ntricolore:::TernaryCenterGrid(c(1/6, 2/6, 3/6), 10)\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/TernaryDistance.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryDistance}\n\\alias{TernaryDistance}\n\\title{Distance Between Points in Ternary Coordinates}\n\\usage{\nTernaryDistance(p, C)\n}\n\\arguments{\n\\item{p}{A vector of ternary coordinates [p1, p2, p3].}\n\n\\item{C}{n by 3 matrix of ternary coordinates [p1, p2, p3](i) for i=1,...,n.}\n}\n\\value{\nA numeric vector of distances between coordinate p and all\n  coordinates in C.\n}\n\\description{\nThe distances between ternary coordinate p and a set of ternary coordinates C.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\np <- c(0.5, 0.2, 0.3)\nC <- prop.table(matrix(runif(3*10), ncol = 3), 1)\ntricolore:::TernaryDistance(p, C)\n\n}\n\\references{\nhttps://en.wikipedia.org/wiki/Barycentric_coordinate_system#Distance_between_points\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/TernaryLimits.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryLimits}\n\\alias{TernaryLimits}\n\\title{Return the Limits of Ternary Coordinates}\n\\usage{\nTernaryLimits(P, na.rm = TRUE)\n}\n\\arguments{\n\\item{P}{n by 3 matrix of ternary coordinates [p1, p2, p3](i) for\ni=1,...,n.}\n\n\\item{na.rm}{Should NAs be removed? (default=TRUE)}\n}\n\\value{\nA 2 by 3 matrix of lower and upper limits for p1, p2 and p3.\n}\n\\description{\nReturn the Limits of Ternary Coordinates\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nP <- prop.table(matrix(runif(9), ncol = 3), 1)\ntricolore:::TernaryLimits(P)\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/TernaryMeshCentroids.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryMeshCentroids}\n\\alias{TernaryMeshCentroids}\n\\title{Centroid Coordinates of Sub-Triangles in Segmented Equilateral Triangle}\n\\usage{\nTernaryMeshCentroids(k)\n}\n\\arguments{\n\\item{k}{Number of rows in the segmented equilateral triangle.}\n}\n\\value{\nA numeric matrix of with index and barycentric centroid coordinates\n  of regions id=1,...,k^2.\n}\n\\description{\nSegment an equilateral triangle into k^2 equilateral sub-triangles and return\nthe barycentric centroid coordinates of each sub-triangle.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\ntricolore:::TernaryMeshCentroids(1)\ntricolore:::TernaryMeshCentroids(2)\ntricolore:::TernaryMeshCentroids(3)\n\n}\n\\references{\nS. H. Derakhshan and C. V. Deutsch (2009): A Color Scale for Ternary Mixtures.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/TernaryMeshVertices.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryMeshVertices}\n\\alias{TernaryMeshVertices}\n\\title{Vertex Coordinates of Sub-Triangles in Segmented Equilateral Triangle}\n\\usage{\nTernaryMeshVertices(C)\n}\n\\arguments{\n\\item{C}{n by 4 matrix of barycentric centroid coordinates of n=k^2\nsub-triangles. Column order: id, p1, p2, p3 with id=1,...,k^2.}\n}\n\\value{\nA numeric matrix with index, vertex id and barycentric vertex\n  coordinates for each of the k^2 sub-triangles.\n}\n\\description{\nGiven the barycentric centroid coordinates of the sub-triangles in an\nequilateral triangle subdivided into k^2 equilateral sub-triangles, return\nthe barycentric vertex coordinates of each sub-triangle.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nk = 2\nC <- tricolore:::TernaryMeshCentroids(k)\ntricolore:::TernaryMeshVertices(C)\n\n}\n\\references{\nS. H. Derakhshan and C. V. Deutsch (2009): A Color Scale for Ternary Mixtures.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/TernaryNearest.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryNearest}\n\\alias{TernaryNearest}\n\\title{For Ternary Coordinates P Return the Nearest Coordinate in Set C}\n\\usage{\nTernaryNearest(P, C)\n}\n\\arguments{\n\\item{P, C}{n by 3 matrix of ternary coordinates [p1, p2, p3](i) for\ni=1,...,n. n may be different for P and C.}\n}\n\\value{\nn by 3 matrix of ternary coordinates in C.\n}\n\\description{\nFor Ternary Coordinates P Return the Nearest Coordinate in Set C\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nP <- prop.table(matrix(runif(9), ncol = 3), 1)\nC <- tricolore:::TernaryMeshCentroids(2)[,-1]\ntricolore:::TernaryNearest(P, C)\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/TernarySextantVertices.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernarySextantVertices}\n\\alias{TernarySextantVertices}\n\\title{Vertex Coordinates of Sextants in Equilateral Triangle}\n\\usage{\nTernarySextantVertices(center)\n}\n\\arguments{\n\\item{center}{The sextant center.\nA vector of ternary coordinates [p1, p2, p3].}\n}\n\\value{\nIndex, vertex id and barycentric vertex coordinates for each of the\n        6 sextants.\n}\n\\description{\nGiven a barycentric center coordinate return the vertex coordinates of the\nof the sextant regions.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\ntricolore:::TernarySextantVertices(rep(1/3, 3))\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/TernarySurroundingSextant.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernarySurroundingSextant}\n\\alias{TernarySurroundingSextant}\n\\title{Return Surrounding Sextant of Barycentric Coordinates}\n\\usage{\nTernarySurroundingSextant(P, center)\n}\n\\arguments{\n\\item{P}{n by 3 matrix of ternary coordinates [p1, p2, p3](i) for\ni=1,...,n.}\n\n\\item{center}{The sextant center.\nA vector of ternary coordinates [p1, p2, p3].}\n}\n\\value{\nAn n element character vector of sextant id's 1 to 6.\n}\n\\description{\nGiven barycentric coordinates return the id of the surrounding sextant.\n}\n\\examples{\n# NOTE: only intended for internal use and not part of the API\nP <- prop.table(matrix(runif(9), ncol = 3), 1)\ntricolore:::TernarySurroundingSextant(P, rep(1/3, 3))\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/Tricolore.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{Tricolore}\n\\alias{Tricolore}\n\\title{Ternary Balance Color Scale}\n\\usage{\nTricolore(\n  df,\n  p1,\n  p2,\n  p3,\n  center = rep(1/3, 3),\n  breaks = ifelse(identical(center, rep(1/3, 3)), 4, Inf),\n  hue = 0.2,\n  chroma = 0.7,\n  lightness = 0.8,\n  contrast = 0.4,\n  spread = 1,\n  legend = TRUE,\n  show_data = TRUE,\n  show_center = ifelse(identical(center, rep(1/3, 3)), FALSE, TRUE),\n  label_as = ifelse(identical(center, rep(1/3, 3)), \"pct\", \"pct_diff\"),\n  crop = FALSE,\n  input_validation = TRUE\n)\n}\n\\arguments{\n\\item{df}{Data frame of compositional data.}\n\n\\item{p1}{Column name for variable in df giving first proportion\nof ternary composition (string).}\n\n\\item{p2}{Column name for variable in df giving second proportion\nof ternary composition (string).}\n\n\\item{p3}{Column name for variable in df giving third proportion\nof ternary composition (string).}\n\n\\item{center}{Ternary coordinates of the color scale center.\n(default = 1/3,1/3,1/3). NA puts center over the compositional\nmean of the data.}\n\n\\item{breaks}{Number of per-axis breaks in the discrete color scale.\nAn integer >1. Values above 99 imply no discretization.}\n\n\\item{hue}{Primary hue of the first ternary element (0 to 1).}\n\n\\item{chroma}{Maximum possible chroma of mixed colors (0 to 1).}\n\n\\item{lightness}{Lightness of mixed colors (0 to 1).}\n\n\\item{contrast}{Lightness contrast of the color scale (0 to 1).}\n\n\\item{spread}{The spread of the color scale. Choose values > 1 to focus the\ncolor scale on the center.}\n\n\\item{legend}{Should a legend be returned along with the colors? (default=TRUE)}\n\n\\item{show_data}{Should the data be shown on the legend? (default=TRUE)}\n\n\\item{show_center}{Should the center be shown on the legend?\n(default=FALSE if center is at c(1/3, 1/3, 1/3), otherwise TRUE)}\n\n\\item{label_as}{\"pct\" for percent-share labels or \"pct_diff\" for\npercent-point-difference from center labels.\n(default='pct' if center is at c(1/3, 1/3, 1/3), otherwise 'pct_diff')}\n\n\\item{crop}{Should the legend be cropped to the data? (default=FALSE)}\n\n\\item{input_validation}{Should the function arguments be validated? (default=TRUE)}\n}\n\\value{\n\\itemize{\n\\item legend=FALSE: A vector of rgbs hex-codes representing the ternary balance\nscheme colors.\n\\item legend=TRUE: A list with elements \"rgb\" and \"key\".\n}\n}\n\\description{\nColor-code three-part compositions with a ternary balance color scale and\nreturn a color key.\n}\n\\examples{\nP <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))\nTricolore(P, 'V1', 'V2', 'V3')\n\n}\n"
  },
  {
    "path": "man/TricoloreSextant.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TricoloreSextant}\n\\alias{TricoloreSextant}\n\\title{Ternary Sextant Color Scale}\n\\usage{\nTricoloreSextant(\n  df,\n  p1,\n  p2,\n  p3,\n  center = rep(1/3, 3),\n  values = c(\"#FFFF00\", \"#B3DCC3\", \"#01A0C6\", \"#B8B3D8\", \"#F11D8C\", \"#FFB3B3\"),\n  legend = TRUE,\n  show_data = TRUE,\n  show_center = TRUE,\n  label_as = ifelse(identical(center, rep(1/3, 3)), \"pct\", \"pct_diff\"),\n  crop = FALSE,\n  input_validation = TRUE\n)\n}\n\\arguments{\n\\item{df}{Data frame of compositional data.}\n\n\\item{p1}{Column name for variable in df giving first proportion\nof ternary composition (string).}\n\n\\item{p2}{Column name for variable in df giving second proportion\nof ternary composition (string).}\n\n\\item{p3}{Column name for variable in df giving third proportion\nof ternary composition (string).}\n\n\\item{center}{Ternary coordinates of the color scale center.\n(default = 1/3,1/3,1/3). NA puts center over the compositional\nmean of the data.}\n\n\\item{values}{6 element character vector of rgb-codes.}\n\n\\item{legend}{Should a legend be returned along with the colors? (default=TRUE)}\n\n\\item{show_data}{Should the data be shown on the legend? (default=TRUE)}\n\n\\item{show_center}{Should the center be shown on the legend?\n(default=FALSE if center is at c(1/3, 1/3, 1/3), otherwise TRUE)}\n\n\\item{label_as}{\"pct\" for percent-share labels or \"pct_diff\" for\npercent-point-difference from center labels.\n(default='pct' if center is at c(1/3, 1/3, 1/3), otherwise 'pct_diff')}\n\n\\item{crop}{Should the legend be cropped to the data? (default=FALSE)}\n\n\\item{input_validation}{Should the function arguments be validated? (default=TRUE)}\n}\n\\value{\n\\itemize{\n\\item legend=FALSE: A vector of rgbs hex-codes representing the ternary balance\nscheme colors.\n\\item legend=TRUE: A list with elements \"rgb\" and \"key\".\n}\n}\n\\description{\nColor-code three-part compositions with a ternary sextant color scale and\nreturn a color key.\n}\n\\examples{\nP <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))\nTricoloreSextant(P, 'V1', 'V2', 'V3')\n\n}\n"
  },
  {
    "path": "man/ValidateMainArguments.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ValidateMainArguments}\n\\alias{ValidateMainArguments}\n\\title{Validate Main Arguments}\n\\usage{\nValidateMainArguments(df, p1, p2, p3)\n}\n\\arguments{\n\\item{df}{Data frame of compositions.}\n\n\\item{p1}{Column name for variable in df giving first proportion\nof ternary composition (string).}\n\n\\item{p2}{Column name for variable in df giving second proportion\nof ternary composition (string.}\n\n\\item{p3}{Column name for variable in df giving third proportion\nof ternary composition (string).}\n}\n\\description{\nValidate main arguments of tricolore function.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/ValidateParametersShared.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ValidateParametersShared}\n\\alias{ValidateParametersShared}\n\\title{Validate Shared Parameters}\n\\usage{\nValidateParametersShared(pars)\n}\n\\arguments{\n\\item{pars}{A named list of parameters.}\n}\n\\description{\nValidate parameters shared across tricolore functions.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/ValidateParametersTricolore.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ValidateParametersTricolore}\n\\alias{ValidateParametersTricolore}\n\\title{Validate Tricolore Parameters}\n\\usage{\nValidateParametersTricolore(pars)\n}\n\\arguments{\n\\item{pars}{A named list of parameters.}\n}\n\\description{\nValidate parameters of Tricolore function.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/ValidateParametersTricoloreSextant.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ValidateParametersTricoloreSextant}\n\\alias{ValidateParametersTricoloreSextant}\n\\title{Validate TricoloreSextant Parameters}\n\\usage{\nValidateParametersTricoloreSextant(pars)\n}\n\\arguments{\n\\item{pars}{A named list of parameters.}\n}\n\\description{\nValidate parameters of TricoloreSextant function.\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/euro_basemap.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\docType{data}\n\\name{euro_basemap}\n\\alias{euro_basemap}\n\\title{Flat Map of European Continent}\n\\format{\nAn object of class \\code{ggplot} (inherits from \\code{ggplot2::ggplot}, \\code{ggplot2::gg}, \\code{S7_object}, \\code{gg}) of length 1.\n}\n\\source{\nDerived from geodata provided by the Natural Earth project.\n  \\url{https://www.naturalearthdata.com/}\n}\n\\usage{\neuro_basemap\n}\n\\description{\nA ggplot object rendering a flat background map of the European continent.\n}\n\\keyword{datasets}\n"
  },
  {
    "path": "man/euro_example.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\docType{data}\n\\name{euro_example}\n\\alias{euro_example}\n\\title{NUTS-2 Level Geodata and Compositional Data for Europe}\n\\format{\nA data frame with 312 rows and 9 variables:\n  \\describe{\n    \\item{id}{NUTS-2 code.}\n    \\item{name}{Name of NUTS-2 region.}\n    \\item{ed_0to2}{Share of population with highest attained education \"lower secondary or less\".}\n    \\item{ed_3to4}{Share of population with highest attained education \"upper secondary\".}\n    \\item{ed_5to8}{Share of population with highest attained education \"tertiary\".}\n    \\item{lf_pri}{Share of labor-force in primary sector.}\n    \\item{lf_sec}{Share of labor-force in secondary sector.}\n    \\item{lf_ter}{Share of labor-force in tertiary sector.}\n    \\item{geometry}{Polygon outlines for regions in sf package format.}\n  }\n}\n\\source{\nDerived from Eurostats European Geodata.\n  (c) EuroGeographics for the administrative boundaries.\n  \\url{https://gisco-services.ec.europa.eu/distribution/v2/nuts/nuts-2016-files.html}\n\n  Education data derived from Eurostats table \"edat_lfse_04\".\n\n  Labor-force data derived from Eurostats table \"lfst_r_lfe2en2\".\n}\n\\usage{\neuro_example\n}\n\\description{\nA simple-features dataframe containing the NUTS-2 level polygons of European\nregions along with regional compositional data on education and labor-force.\n}\n\\details{\nVariables starting with \"ed\" refer to the relative share of population ages\n  25 to 64 by educational attainment in the European NUTS-2 regions 2016.\n\n  Variables starting with \"lf\" refer to the relative share of workers by\n  labor-force sector in the European NUTS-2 regions 2016. The original NACE\n  (rev. 2) codes have been recoded into the three sectors \"primary\" (A),\n  \"secondary\" (B-E & F) and \"tertiary\" (all other NACE codes).\n}\n\\keyword{datasets}\n"
  },
  {
    "path": "tests/testthat/test-global.R",
    "content": "context('test-global.R')\n\ntest_that('GeometricMean() works', {\n  expect_equal(GeometricMean(0:4), exp(mean(log(1:4))))\n  expect_equal(GeometricMean(0:4, zero.rm = FALSE), 0)\n  expect_equal(GeometricMean(c(NA, 0:4), na.rm = TRUE, zero.rm = FALSE), 0)\n  expect_equal(GeometricMean(c(NA, 0:4), na.rm = FALSE, zero.rm = FALSE), as.numeric(NA))\n  expect_equal(GeometricMean(0:4, na.rm = FALSE, zero.rm = TRUE), exp(mean(log(1:4))))\n  expect_equal(GeometricMean(c(NA, 0:4), na.rm = FALSE, zero.rm = TRUE), as.numeric(NA))\n  expect_equal(GeometricMean(0, zero.rm = TRUE), NaN)\n})\n\ntest_that('Centre() works', {\n  P <- prop.table(matrix(runif(300), 100), margin = 1)\n  expect_equal(prop.table(apply(t(t(P)/Centre(P)), 2, GeometricMean)), rep(1/3, 3))\n  expect_equal(NROW(Centre(P)), 3)\n  expect_equal(NCOL(Centre(P)), 1)\n})\n\n\ntest_that('Pertube() works', {\n  P <- prop.table(matrix(runif(300), 100), margin = 1)\n  expect_equal(Pertube(P, rep(1/3, 3)), P)\n  expect_equal(Centre(Pertube(P, 1/Centre(P))), rep(1/3, 3))\n  expect_equal(NROW(Pertube(P, rep(1/3, 3))), 100)\n  expect_equal(NCOL(Pertube(P, rep(1/3, 3))), 3)\n})\n\ntest_that('TernaryMeshCentroids() works', {\n  k = sample(2:100, size = 1)\n  expect_equal(NROW(TernaryMeshCentroids(k)), k^2)\n  expect_equal(TernaryMeshCentroids(k)[,'id'], 1:k^2)\n  expect_equal(rowSums(TernaryMeshCentroids(k)[,2:4]), rep(1, k^2))\n  expect_equivalent(prop.table(apply(TernaryMeshCentroids(k)[,2:4], 2, GeometricMean)), rep(1/3, 3))\n})\n\ntest_that('Argument checks work', {\n  P <- as.data.frame(prop.table(matrix(runif(300), 100), margin = 1))\n  # missing main arguments\n  expect_error(Tricolore(p1 = 'V1', p2 = 'V2', p3 = 'V3'),\n               'main argument missing')\n  expect_error(Tricolore(P, p2 = 'V2', p3 = 'V3'),\n               'main argument missing')\n  expect_error(Tricolore(P, p1 = 'V1', p3 = 'V3'),\n               'main argument missing')\n  expect_error(Tricolore(P, p1 = 'V1', p2 = 'V2'),\n               'main argument missing')\n  expect_error(Tricolore(P, p1 = 'Foo1', p2 = 'V2', p3 = 'V3'),\n               'Foo1 not found')\n  expect_error(Tricolore(P, p1 = 'V1', p2 = 'Foo2', p3 = 'V3'),\n               'Foo2 not found')\n  expect_error(Tricolore(P, p1 = 'V1', p2 = 'V2', p3 = 'Foo3'),\n               'Foo3 not found')\n  # type checks for main arguments\n  expect_error(Tricolore(as.matrix(P), p1 = 'V1', p2 = 'V2', p3 = 'V3'),\n               'df is not a data frame')\n  expect_error(Tricolore(P, p1 = 1, p2 = 2, p3 = 3),\n               'not a string')\n  expect_error(Tricolore(data.frame(V1 = as.character(P$V1), V2 = P$V2, V3 = P$V3),\n                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),\n               'variable V1 is not numeric')\n  expect_error(Tricolore(data.frame(V1 = P$V1, V2 = as.character(P$V2), V3 = P$V3),\n                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),\n               'variable V2 is not numeric')\n  expect_error(Tricolore(data.frame(V1 = P$V1, V2 = P$V2, V3 = as.character(P$V3)),\n                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),\n               'variable V3 is not numeric')\n  expect_error(Tricolore(data.frame(V1 = -P$V1, V2 = P$V2, V3 = P$V3),\n                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),\n               'variable V1 contains negative values')\n  expect_error(Tricolore(data.frame(V1 = P$V1, V2 = -P$V2, V3 = P$V3),\n                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),\n               'variable V2 contains negative values')\n  expect_error(Tricolore(data.frame(V1 = P$V1, V2 = P$V2, V3 = -P$V3),\n                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),\n               'variable V3 contains negative values')\n})\n\n# NA, Inf, NaN are allowed and are expected to return NA as color\ntest_that('NA, Inf, NaNs in input return NA in output', {\n  P <- data.frame(a = c(1, NA), b = c(0, 0.5), c = c(0, 0.2))\n  tric <- Tricolore(P, 'a', 'b', 'c', breaks = Inf)\n  expect_equal(tric$rgb, c('#F0C500', NA))\n  expect_true(all(c('gg', 'ggplot') %in% class(tric$key)))\n  P <- data.frame(a = c(1, Inf), b = c(0, 0.5), c = c(0, 0.2))\n  tric <- Tricolore(P, 'a', 'b', 'c', breaks = Inf)\n  expect_equal(tric$rgb, c('#F0C500', NA))\n  expect_true(all(c('gg', 'ggplot') %in% class(tric$key)))\n  P <- data.frame(a = c(1, NaN), b = c(0, 0.5), c = c(0, 0.2))\n  tric <- Tricolore(P, 'a', 'b', 'c', breaks = Inf)\n  expect_equal(tric$rgb, c('#F0C500', NA))\n  expect_true(all(c('gg', 'ggplot') %in% class(tric$key)))\n})\n"
  },
  {
    "path": "tests/testthat.R",
    "content": "library(testthat)\nlibrary(tricolore)\n\ntest_check('tricolore')\n"
  },
  {
    "path": "vignettes/choropleth_maps_with_tricolore.R",
    "content": "## ----setup, include = FALSE---------------------------------------------------\nknitr::opts_chunk$set(\n  collapse = TRUE,\n  tidy = FALSE,\n  comment = \"#>\",\n  fig.width = 6, fig.height = 6\n)\n\n## -----------------------------------------------------------------------------\nlibrary(tricolore)\n\n## -----------------------------------------------------------------------------\n# color-code the data set and generate a color-key\ntric <- Tricolore(euro_example, p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8')\n\n## -----------------------------------------------------------------------------\n# add the vector of colors to the `euro_example` data\neuro_example$rgb <- tric$rgb\n\n## -----------------------------------------------------------------------------\nlibrary(ggplot2)\n\nplot_educ <-\n  # using sf dataframe `euro_example`...\n  ggplot(euro_example) +\n  # ...draw a polygon for each region...\n  geom_sf(aes(fill = rgb, geometry = geometry), size = 0.1) +\n  # ...and color each region according to the color code in the variable `rgb`\n  scale_fill_identity()\n\nplot_educ \n\n## -----------------------------------------------------------------------------\nlibrary(ggtern)\nplot_educ +\n  annotation_custom(\n    ggplotGrob(tric$key),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  )\n\n## -----------------------------------------------------------------------------\nplot_educ <-\n  plot_educ +\n  annotation_custom(\n    ggplotGrob(tric$key +\n                 theme(plot.background = element_rect(fill = NA, color = NA)) +\n                 labs(L = '0-2', T = '3-4', R = '5-8')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  )\nplot_educ\n\n## -----------------------------------------------------------------------------\nplot_educ +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(\n   title = 'European inequalities in educational attainment',\n      subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.'\n  )\n\n## -----------------------------------------------------------------------------\n# color-code the data set and generate a color-key\ntric <- Tricolore(euro_example, p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',\n                  breaks = Inf)\n\n# add the vector of colors to the `euro_example` data\neuro_example$rgb <- tric$rgb\n\n## -----------------------------------------------------------------------------\nlibrary(sf)\nlibrary(leaflet)\n\neuro_example %>%\n  st_transform(crs = 4326) %>%\n  leaflet() %>%\n  addPolygons(smoothFactor = 0.1, weight = 0,\n              fillColor = euro_example$rgb,\n              fillOpacity = 1)\n\n## -----------------------------------------------------------------------------\neuro_example %>%\n  st_transform(crs = 4326) %>%\n  leaflet() %>%\n  addProviderTiles(providers$Esri.WorldTerrain) %>%\n  addPolygons(smoothFactor = 0.1, weight = 0,\n              fillColor = euro_example$rgb,\n              fillOpacity = 1,\n              popup =\n                paste0(\n                  '<b>', euro_example$name, '</b></br>',\n                  'Primary: ',\n                  formatC(euro_example$ed_0to2*100,\n                          digits = 1, format = 'f'), '%</br>',\n                  'Secondary: ',\n                  formatC(euro_example$ed_3to4*100,\n                          digits = 1, format = 'f'), '%</br>',\n                  'Tertiary: ',\n                  formatC(euro_example$ed_5to8*100,\n                          digits = 1, format = 'f'), '%</br>'\n                )\n  )\n\n## -----------------------------------------------------------------------------\nmakePlotURI <- function(expr, width, height, ...) {\n  pngFile <- shiny::plotPNG(function() { expr }, width = width, height = height, ...)\n  on.exit(unlink(pngFile))\n\n  base64 <- httpuv::rawToBase64(readBin(pngFile, raw(1), file.size(pngFile)))\n  paste0(\"data:image/png;base64,\", base64)\n}\n\nlegend_symbol <- makePlotURI({\n  print(tric$key +\n          theme(plot.background = element_rect(fill = NA, color = NA)) +\n          labs(L = '0-2', T = '3-4', R = '5-8'))\n}, 200, 200, bg = \"transparent\")\n\ndf <- data.frame(\n  lng = 30,\n  lat = 70,\n  plot = legend_symbol,\n  stringsAsFactors = FALSE\n)\n\neuro_example %>%\n  st_transform(crs = 4326) %>%\n  leaflet() %>%\n  addProviderTiles(providers$Esri.WorldGrayCanvas) %>%\n  addPolygons(smoothFactor = 0.1, weight = 0,\n              fillColor = euro_example$rgb,\n              fillOpacity = 1,\n              popup =\n                paste0(\n                  '<b>', euro_example$name, '</b></br>',\n                  'Primary: ',\n                  formatC(euro_example$ed_0to2*100,\n                          digits = 1, format = 'f'), '%</br>',\n                  'Secondary: ',\n                  formatC(euro_example$ed_3to4*100,\n                          digits = 1, format = 'f'), '%</br>',\n                  'Tertiary: ',\n                  formatC(euro_example$ed_5to8*100,\n                          digits = 1, format = 'f'), '%</br>'\n                )\n  ) %>%\n  addMarkers(data = df, icon = ~icons(plot))\n\n"
  },
  {
    "path": "vignettes/choropleth_maps_with_tricolore.Rmd",
    "content": "---\ntitle: \"Choropleth maps with tricolore\"\nauthor: \"Jonas Schöley\"\ndate: \"`r Sys.Date()`\"\noutput: rmarkdown::html_vignette\nvignette: >\n  %\\VignetteIndexEntry{Choropleth maps with tricolore}\n  %\\VignetteEngine{knitr::rmarkdown}\n  %\\VignetteEncoding{UTF-8}\n  %\\VignetteDepends{shiny, sf, leaflet, tricolore, dplyr, ggplot2, ggtern, httpuv}\n---\n\n```{r setup, include = FALSE}\nknitr::opts_chunk$set(\n  collapse = TRUE,\n  tidy = FALSE,\n  comment = \"#>\",\n  fig.width = 6, fig.height = 6\n)\n```\n\nHere I demonstrate how to use the `tricolore` library to generate ternary choropleth maps using both `ggplot2` and `leaflet`.\n\nThe data\n--------\n\n```{r}\nlibrary(tricolore)\n```\n\nThe data set `euro_example` contains the administrative boundaries for the European NUTS-2 regions in the column `geometry`. This data can be used to plot a choropleth map of Europe using the `sf` package. Each region is represented by a single row. The name of a region is given by the variable `name` while the respective [NUTS-2](https://en.wikipedia.org/wiki/Nomenclature_of_Territorial_Units_for_Statistics) geocode is given by the variable `id`. For each region some compositional statistics are available: Variables starting with `ed` refer to the relative share of population ages 25 to 64 by educational attainment in 2016 and variables starting with `lf` refer to the relative share of workers by labor-force sector in the European NUTS-2 regions 2016.\n\nTake the first row of the data set as an example: in the Austrian region of \"Burgenland\" (`id` = `AT11`) 16.5% of the population aged 25--64 had attained an education of \"Lower secondary or less\" (`ed_0to2`), 55.7% attained \"upper secondary\" education (`ed_3to4`), and 27.9% attained \"tertiary\" education. In the very same region 4.4% of the labor-force works in the primary sector, 26.8% in the secondary and 68.2% in the tertiary sector.\n\nThe education and labor-force compositions are *ternary*, i.e. made up from three elements, and therefore can be color-coded as the weighted mixture of three primary colors, each primary mapped to one of the three elements. Such a color scale is called a *ternary balance scheme*^[See for example Dorling (2012) and Brewer (1994).]. This is what `tricolore` does.\n\n`ggplot2` for ternary choropleth maps\n-------------------------------------\n\nHere I show how to create a choropleth map of the regional distribution of education attainment in Europe 2016 using `ggplot2`.\n\n**1. Using the `Tricolore()` function, color-code each educational composition in the `euro_example` data set and add the resulting vector of hex-srgb colors as a new variable to the data frame. Store the color key separately.**\n\n```{r}\n# color-code the data set and generate a color-key\ntric <- Tricolore(euro_example, p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8')\n```\n\n`tric` contains both a vector of color-coded compositions (`tric$rgb`) and the corresponding color key (`tric$key`). We add the vector of colors to the map-data.\n\n```{r}\n# add the vector of colors to the `euro_example` data\neuro_example$rgb <- tric$rgb\n```\n\n**2. Using `ggplot2` and the joined color-coded education data and geodata, plot a ternary choropleth map of education attainment in the European regions. Add the color key to the map.**\n\nThe secret ingredient is `scale_fill_identity()` to make sure that each region is colored according to the value in the `rgb` variable of `euro_educ_map`.\n\n```{r}\nlibrary(ggplot2)\n\nplot_educ <-\n  # using sf dataframe `euro_example`...\n  ggplot(euro_example) +\n  # ...draw a polygon for each region...\n  geom_sf(aes(fill = rgb, geometry = geometry), size = 0.1) +\n  # ...and color each region according to the color code in the variable `rgb`\n  scale_fill_identity()\n\nplot_educ \n```\n\nUsing `annotation_custom()` and `ggplotGrob` we can add the color key produced by `Tricolore()` to the map. Internally, the color key is produced with the [`ggtern`](https://CRAN.R-project.org/package=ggtern) package. In order for it to render correctly we need to load `ggtern` *after* loading `ggplot2`. Don't worry, the `ggplot2` functions still work.\n\n```{r}\nlibrary(ggtern)\nplot_educ +\n  annotation_custom(\n    ggplotGrob(tric$key),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  )\n```\n\nBecause the color key behaves just like a `ggplot2` plot we can change it to our liking.\n\n```{r}\nplot_educ <-\n  plot_educ +\n  annotation_custom(\n    ggplotGrob(tric$key +\n                 theme(plot.background = element_rect(fill = NA, color = NA)) +\n                 labs(L = '0-2', T = '3-4', R = '5-8')),\n    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5\n  )\nplot_educ\n```\n\nSome final touches...\n\n```{r}\nplot_educ +\n  theme_void() +\n  coord_sf(datum = NA) +\n  labs(\n   title = 'European inequalities in educational attainment',\n      subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.'\n  )\n```\n\n`leaflet` for ternary choropleth maps\n-------------------------------------\n\nThe `ggplot2` example above is easily adapted to `leaflet`. This time I use a continuous color scale.\n\n```{r}\n# color-code the data set and generate a color-key\ntric <- Tricolore(euro_example, p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',\n                  breaks = Inf)\n\n# add the vector of colors to the `euro_example` data\neuro_example$rgb <- tric$rgb\n```\n\n`leaflet` requires geodata in spherical coordinates (longitude-latitude format). Therefore I reproject the data to a [suitable crs](https://spatialreference.org/ref/epsg/4326/) using the `sf` package.\n\n```{r}\nlibrary(sf)\nlibrary(leaflet)\n\neuro_example %>%\n  st_transform(crs = 4326) %>%\n  leaflet() %>%\n  addPolygons(smoothFactor = 0.1, weight = 0,\n              fillColor = euro_example$rgb,\n              fillOpacity = 1)\n```\n\nAdding a background map gives geographical context to the map. I also add a mouse pop-up of the actual data.\n\n```{r}\neuro_example %>%\n  st_transform(crs = 4326) %>%\n  leaflet() %>%\n  addProviderTiles(providers$Esri.WorldTerrain) %>%\n  addPolygons(smoothFactor = 0.1, weight = 0,\n              fillColor = euro_example$rgb,\n              fillOpacity = 1,\n              popup =\n                paste0(\n                  '<b>', euro_example$name, '</b></br>',\n                  'Primary: ',\n                  formatC(euro_example$ed_0to2*100,\n                          digits = 1, format = 'f'), '%</br>',\n                  'Secondary: ',\n                  formatC(euro_example$ed_3to4*100,\n                          digits = 1, format = 'f'), '%</br>',\n                  'Tertiary: ',\n                  formatC(euro_example$ed_5to8*100,\n                          digits = 1, format = 'f'), '%</br>'\n                )\n  )\n```\n\nAdding the legend to the leaflet map requires a bit of a [hack](https://github.com/rstudio/leaflet/issues/51#issuecomment-213108125).\n\n```{r}\nmakePlotURI <- function(expr, width, height, ...) {\n  pngFile <- shiny::plotPNG(function() { expr }, width = width, height = height, ...)\n  on.exit(unlink(pngFile))\n\n  base64 <- httpuv::rawToBase64(readBin(pngFile, raw(1), file.size(pngFile)))\n  paste0(\"data:image/png;base64,\", base64)\n}\n\nlegend_symbol <- makePlotURI({\n  print(tric$key +\n          theme(plot.background = element_rect(fill = NA, color = NA)) +\n          labs(L = '0-2', T = '3-4', R = '5-8'))\n}, 200, 200, bg = \"transparent\")\n\ndf <- data.frame(\n  lng = 30,\n  lat = 70,\n  plot = legend_symbol,\n  stringsAsFactors = FALSE\n)\n\neuro_example %>%\n  st_transform(crs = 4326) %>%\n  leaflet() %>%\n  addProviderTiles(providers$Esri.WorldGrayCanvas) %>%\n  addPolygons(smoothFactor = 0.1, weight = 0,\n              fillColor = euro_example$rgb,\n              fillOpacity = 1,\n              popup =\n                paste0(\n                  '<b>', euro_example$name, '</b></br>',\n                  'Primary: ',\n                  formatC(euro_example$ed_0to2*100,\n                          digits = 1, format = 'f'), '%</br>',\n                  'Secondary: ',\n                  formatC(euro_example$ed_3to4*100,\n                          digits = 1, format = 'f'), '%</br>',\n                  'Tertiary: ',\n                  formatC(euro_example$ed_5to8*100,\n                          digits = 1, format = 'f'), '%</br>'\n                )\n  ) %>%\n  addMarkers(data = df, icon = ~icons(plot))\n```\n\nLiterature\n----------\n\nBrewer, C. A. (1994). Color Use Guidelines for Mapping and Visualization. In A. M. MacEachren & D. R. F. Taylor (Eds.), Visualization in Modern Cartography (pp. 123–147). Oxford, UK: Pergamon.\n\nDorling, D. (2012). The Visualization of Spatial Social Structure. Chichester, UK: Wiley.\n\nSchöley, J. (2021). The centered ternary balance scheme: A technique to visualize surfaces of unbalanced three-part compositions. Demographic Research (44).\n"
  }
]