Full Code of jschoeley/tricolore for AI

master 2e722f37844f cached
55 files
171.8 KB
48.7k tokens
1 requests
Download .txt
Repository: jschoeley/tricolore
Branch: master
Commit: 2e722f37844f
Files: 55
Total size: 171.8 KB

Directory structure:
gitextract_ffmohb3v/

├── .Rbuildignore
├── .github/
│   ├── .gitignore
│   └── workflows/
│       └── R-CMD-check.yaml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── CRAN-SUBMISSION
├── DESCRIPTION
├── LICENSE
├── NAMESPACE
├── NEWS.md
├── R/
│   ├── tricolore.R
│   └── zzz.R
├── README.Rmd
├── README.md
├── cran-comments.md
├── data/
│   ├── euro_basemap.RData
│   └── euro_example.RData
├── data-raw/
│   ├── euro_basemap.R
│   ├── euro_basemap.RData
│   ├── euro_example.R
│   └── euro_example.RData
├── inst/
│   ├── CITATION
│   └── shiny/
│       └── app.R
├── man/
│   ├── BasicKey.Rd
│   ├── BreaksAndLabels.Rd
│   ├── Centre.Rd
│   ├── ColorKeySextant.Rd
│   ├── ColorKeyTricolore.Rd
│   ├── ColorMapSextant.Rd
│   ├── ColorMapTricolore.Rd
│   ├── DemoTricolore.Rd
│   ├── GeometricMean.Rd
│   ├── Pertube.Rd
│   ├── PowerScale.Rd
│   ├── TernaryCenterGrid.Rd
│   ├── TernaryDistance.Rd
│   ├── TernaryLimits.Rd
│   ├── TernaryMeshCentroids.Rd
│   ├── TernaryMeshVertices.Rd
│   ├── TernaryNearest.Rd
│   ├── TernarySextantVertices.Rd
│   ├── TernarySurroundingSextant.Rd
│   ├── Tricolore.Rd
│   ├── TricoloreSextant.Rd
│   ├── ValidateMainArguments.Rd
│   ├── ValidateParametersShared.Rd
│   ├── ValidateParametersTricolore.Rd
│   ├── ValidateParametersTricoloreSextant.Rd
│   ├── euro_basemap.Rd
│   └── euro_example.Rd
├── tests/
│   ├── testthat/
│   │   └── test-global.R
│   └── testthat.R
└── vignettes/
    ├── choropleth_maps_with_tricolore.R
    └── choropleth_maps_with_tricolore.Rmd

================================================
FILE CONTENTS
================================================

================================================
FILE: .Rbuildignore
================================================
^.*\.Rproj$
^\.Rproj\.user$
priv
README_files
README.md
README.R
data-raw
TODO.txt
examples
^cran-comments\.md$
CODE_OF_CONDUCT.md
LICENSE
CONTRIBUTING.md
^CRAN-RELEASE$
^\.github$
^CRAN-SUBMISSION$


================================================
FILE: .github/.gitignore
================================================
*.html


================================================
FILE: .github/workflows/R-CMD-check.yaml
================================================
# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on:
  push:
    branches: [main, master, devel]
  pull_request:
    branches: [main, master, devel]

name: R-CMD-check

jobs:
  R-CMD-check:
    runs-on: ${{ matrix.config.os }}

    name: ${{ matrix.config.os }} (${{ matrix.config.r }})

    strategy:
      fail-fast: false
      matrix:
        config:
          - {os: macos-latest,   r: 'release'}
          - {os: windows-latest, r: 'release'}
          - {os: ubuntu-latest,   r: 'devel', http-user-agent: 'release'}
          - {os: ubuntu-latest,   r: 'release'}
          - {os: ubuntu-latest,   r: 'oldrel-1'}

    env:
      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
      R_KEEP_PKG_SOURCE: yes

    steps:
      - uses: actions/checkout@v3

      - uses: r-lib/actions/setup-pandoc@v2

      - uses: r-lib/actions/setup-r@v2
        with:
          r-version: ${{ matrix.config.r }}
          http-user-agent: ${{ matrix.config.http-user-agent }}
          use-public-rspm: true

      - uses: r-lib/actions/setup-r-dependencies@v2
        with:
          extra-packages: any::rcmdcheck
          needs: check

      - uses: r-lib/actions/check-r-package@v2
        with:
          upload-snapshots: true
          args: 'c("--no-manual", "--as-cran")'


================================================
FILE: .gitignore
================================================
# General ---------------------------------------------------------------------

priv
# R specific ------------------------------------------------------------------
# History files
.Rhistory
.Rapp.history
# Example code in package build process
*-Ex.R
# RStudio files
.Rproj.user/
.Rproj.user
*.Rproj
# produced vignettes
vignettes/*.html
vignettes/*.pdf
# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3
.httr-oauth
# cached Rmarkdown files
*_cache
# Rpubs
rsconnect
inst/doc


================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct

## Our Pledge

In 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.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project 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.

Project 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.

## Scope

This 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.

## Enforcement

Instances 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.

Project 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.

## Attribution

This 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

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq


================================================
FILE: CONTRIBUTING.md
================================================
Contributing to `tricolore`
---------------------------

*This guide is adapted from the `devtools` template*

The 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:

1. Filing a bug report or feature request in an issue.
2. Suggesting a change via a pull request.

## Issues

Before you file an issue:

1. Check that you're using the latest version of `tricolore`. It's quite possible that the problem you're experiencing has already been fixed.
2. Check that the issue belongs in `tricolore`. Much functionality now lives in separate packages (e.g. `ggtern`).
3. 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.

When 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.

1. **Packages** should be loaded at the top of the script, so it's easy to see which ones the example needs.
2. 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:
       1. Run `dput(mtcars)` in R
       2. Copy the output
       3. In my reproducible script, type `mtcars <- ` then paste.
    But even better is if you can create a `data.frame()` with just a handful of rows and columns that still illustrates the problem.
3. Spend a little bit of time ensuring that your **code** is easy for others to read:
  * make sure you've used spaces and your variable names are concise, but informative
  * use comments to indicate where your problem lies
  * do your best to remove everything that is not related to the problem. The shorter your code is, the easier it is to understand.
  * 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).
4. Check that you've actually made a reproducible example by using the [reprex package](https://github.com/jennybc/reprex).

## Pull requests

* 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.

* 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.

* If you propose a new feature, write a test for it.

* 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.

A 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:

1. You submit the pull request.

2. 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.
    
3. We'll take a closer look at the code and give you feedback.

4. 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.

Don't worry if your pull request isn't perfect. It's a learning process and we'll be happy to help you out.

[markdown]: https://help.github.com/articles/basic-writing-and-formatting-syntax/

================================================
FILE: CRAN-SUBMISSION
================================================
Version: 1.2.4
Date: 2024-05-14 13:32:45 UTC
SHA: c4f25b8a52e7e6ca54bf876796e1e0f9b4432a9e


================================================
FILE: DESCRIPTION
================================================
Package: tricolore
Type: Package
Title: A Flexible Color Scale for Ternary Compositions
Version: 1.2.6
Authors@R: c(
  person(
    "Jonas", "Schöley", email = "jschoeley@gmail.com", role = c("aut", "cre"),
    comment = c(ORCID = "0000-0002-3340-8518")
  ),
  person(
    "Ilya", "Kashnitsky", role = c("aut"),
    comment = c(ORCID = "0000-0003-1835-8687")
  ))
Description: Compositional data consisting of three-parts can be color
  mapped with a ternary color scale. Such a scale is provided by
  the tricolore packages with options for discrete and continuous
  colors, mean-centering and scaling. See 
  Jonas Schöley (2021) "The centered ternary balance scheme. A technique
  to visualize surfaces of unbalanced three-part compositions"
  <doi:10.4054/DemRes.2021.44.19>,
  Jonas Schöley, Frans Willekens (2017) "Visualizing compositional data
  on the Lexis surface" <doi:10.4054/DemRes.2017.36.21>, and
  Ilya Kashnitsky, Jonas Schöley (2018) "Regional population structures
  at a glance" <doi:10.1016/S0140-6736(18)31194-2>.
License: GPL-3
URL: https://github.com/jschoeley/tricolore
Encoding: UTF-8
LazyData: true
Depends: R (>= 4.0)
Imports: grDevices, ggplot2 (>= 4.0.0), ggtern (>= 4.0.0), rlang (>= 1.1.0), shiny, assertthat
RoxygenNote: 7.3.3
Suggests: testthat, knitr, rmarkdown, sf, leaflet, httpuv, dplyr
VignetteBuilder: knitr


================================================
FILE: LICENSE
================================================
### GNU GENERAL PUBLIC LICENSE

Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.

### Preamble

The GNU General Public License is a free, copyleft license for
software and other kinds of works.

The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom
to share and change all versions of a program--to make sure it remains
free software for all its users. We, the Free Software Foundation, use
the GNU General Public License for most of our software; it applies
also to any other work released this way by its authors. You can apply
it to your programs, too.

When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you
have certain responsibilities if you distribute copies of the
software, or if you modify it: responsibilities to respect the freedom
of others.

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.

Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so. This is fundamentally incompatible with the
aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those
domains in future versions of the GPL, as needed to protect the
freedom of users.

Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish
to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL
assures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and
modification follow.

### TERMS AND CONDITIONS

#### 0. Definitions.

"This License" refers to version 3 of the GNU General Public License.

"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.

"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.

To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.

A "covered work" means either the unmodified Program or a work based
on the Program.

To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.

An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

#### 1. Source Code.

The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.

A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.

The Corresponding Source for a work in source code form is that same
work.

#### 2. Basic Permissions.

All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.

Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.

#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.

No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.

#### 4. Conveying Verbatim Copies.

You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

#### 5. Conveying Modified Source Versions.

You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:

-   a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.
-   b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under
    section 7. This requirement modifies the requirement in section 4
    to "keep intact all notices".
-   c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy. This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged. This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.
-   d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

#### 6. Conveying Non-Source Forms.

You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:

-   a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.
-   b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the Corresponding
    Source from a network server at no charge.
-   c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source. This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.
-   d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge. You need not require recipients to copy the
    Corresponding Source along with the object code. If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source. Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.
-   e) Convey the object code using peer-to-peer transmission,
    provided you inform other peers where the object code and
    Corresponding Source of the work are being offered to the general
    public at no charge under subsection 6d.

A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.

"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.

If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.

Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

#### 7. Additional Terms.

"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:

-   a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or
-   b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or
-   c) Prohibiting misrepresentation of the origin of that material,
    or requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or
-   d) Limiting the use for publicity purposes of names of licensors
    or authors of the material; or
-   e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or
-   f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions
    of it) with contractual assumptions of liability to the recipient,
    for any liability that these contractual assumptions directly
    impose on those licensors and authors.

All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.

#### 8. Termination.

You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.

Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

#### 9. Acceptance Not Required for Having Copies.

You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

#### 10. Automatic Licensing of Downstream Recipients.

Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.

An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

#### 11. Patents.

A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".

A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.

Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

#### 12. No Surrender of Others' Freedom.

If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.

#### 13. Use with the GNU Affero General Public License.

Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

#### 14. Revised Versions of this License.

The Free Software Foundation may publish revised and/or new versions
of the GNU General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU General Public
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that numbered version or
of any later version published by the Free Software Foundation. If the
Program does not specify a version number of the GNU General Public
License, you may choose any version ever published by the Free
Software Foundation.

If the Program specifies that a proxy can decide which future versions
of the GNU General Public License can be used, that proxy's public
statement of acceptance of a version permanently authorizes you to
choose that version for the Program.

Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

#### 15. Disclaimer of Warranty.

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

#### 16. Limitation of Liability.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

#### 17. Interpretation of Sections 15 and 16.

If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

END OF TERMS AND CONDITIONS

### How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.

To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.

        <one line to give the program's name and a brief idea of what it does.>
        Copyright (C) <year>  <name of author>

        This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper
mail.

If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

        <program>  Copyright (C) <year>  <name of author>
        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
        This is free software, and you are welcome to redistribute it
        under certain conditions; type `show c' for details.

The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, your
program's commands might be different; for a GUI interface, you would
use an "about box".

You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU GPL, see <https://www.gnu.org/licenses/>.

The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
GNU Lesser General Public License instead of this License. But first,
please read <https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: NAMESPACE
================================================
# Generated by roxygen2: do not edit by hand

export(DemoTricolore)
export(Tricolore)
export(TricoloreSextant)
importFrom(assertthat,assert_that)
importFrom(assertthat,is.flag)
importFrom(assertthat,is.number)
importFrom(assertthat,is.scalar)
importFrom(assertthat,is.string)
importFrom(ggplot2,element_text)
importFrom(ggplot2,labs)
importFrom(ggplot2,layer)
importFrom(ggplot2,scale_color_identity)
importFrom(ggplot2,scale_fill_identity)
importFrom(ggplot2,theme)
importFrom(ggtern,aes)
importFrom(ggtern,geom_Lline)
importFrom(ggtern,geom_Rline)
importFrom(ggtern,geom_Tline)
importFrom(ggtern,geom_mask)
importFrom(ggtern,ggtern)
importFrom(ggtern,scale_L_continuous)
importFrom(ggtern,scale_R_continuous)
importFrom(ggtern,scale_T_continuous)
importFrom(ggtern,theme_classic)
importFrom(grDevices,hcl)
importFrom(grDevices,hsv)
importFrom(rlang,.data)


================================================
FILE: NEWS.md
================================================
# tricolore 1.2.6

* establish compatibility with ggplot/ggtern 4.0.0

# tricolore 1.2.5

* re-export `euro_basemap.RData` to fix (@clementviolet, #24)

# tricolore 1.2.4

* establish compatibility with ggplot/ggtern 3.4.2
* update deprecated ggplot code
* update outdated crs spec in example data
* add Schöley (2021) reference to vignette

# tricolore 1.2.3

* add startup message and citation information
* establish compatibility with ggplot2 3.3.4/3.3.5 (@hhmacedo, #13)

# tricolore 1.2.2

* establish compatibility with ggplot/ggtern 3.3.0
* remove 'caption' labels from example plots as it causes rendering bug

# tricolore 1.2.1

* establish compatibility with ggplot/ggtern 3.2.0
* allow TricoloreDemo() to run as stand-alone shiny-app (i.e. on shinyapps server)

# tricolore 1.2.0

* allow for discrete re-centered scales
* add new discrete scales TricoloreSextant
* reorder Tricolore*() arguments
* rename Tricolore*() list output to `rgb` and `key`
* add new features to shiny app

# tricolore 1.1.1

* make TernaryLimits() internal

# tricolore 1.1.0

* change defaults
* make defaults dynamic
* remove alpha part from rgb codes

# tricolore 1.0.8

* add legend crop option
* update README
* add dependencies to travis recipe

# tricolore 1.0.7

* add dependencies to travis recipe

# tricolore 1.0.6

* provide example data as sf data frame
* use sf in the examples
* add choropleth maps with tricolore vignette featuring leaflets

# tricolore 1.0.5

* add option for percent-point difference labeling in ternary legend
* add tests

# tricolore 1.0.4

* establish compatibility with ggplot/ggtern 3.0.0

# tricolore 1.0.3

* Initial CRAN release


================================================
FILE: R/tricolore.R
================================================
# Misc --------------------------------------------------------------------

# from nnet::which.is.max()
MaxIndex <- function (x) {
  y <- seq_along(x)[x == max(x)]
  if (length(y) > 1L) { sample(y, 1L) } else { y }
}

#' Validate Main Arguments
#'
#' Validate main arguments of tricolore function.
#'
#' @param df Data frame of compositions.
#' @param p1 Column name for variable in df giving first proportion
#'           of ternary composition (string).
#' @param p2 Column name for variable in df giving second proportion
#'           of ternary composition (string.
#' @param p3 Column name for variable in df giving third proportion
#'           of ternary composition (string).
#'
#' @importFrom assertthat assert_that is.string
#'
#' @keywords internal
ValidateMainArguments <- function (df, p1, p2, p3) {

  # missing arguments
  assert_that(!missing(df), !missing(p1), !missing(p2), !missing(p3),
              msg = 'main argument missing')
  # compositional data is data frame
  assert_that(is.data.frame(df))
  # variable names as strings
  assert_that(is.string(p1), is.string(p2), is.string(p3))
  # missing variables in data frame
  assert_that(p1 %in% names(df), msg = paste('variable', p1 ,'not found in df'))
  assert_that(p2 %in% names(df), msg = paste('variable', p2 ,'not found in df'))
  assert_that(p3 %in% names(df), msg = paste('variable', p3 ,'not found in df'))
  # compositional data is numeric
  assert_that(is.numeric(df[[p1]]), msg = paste('variable', p1 ,'is not numeric'))
  assert_that(is.numeric(df[[p2]]), msg = paste('variable', p2 ,'is not numeric'))
  assert_that(is.numeric(df[[p3]]), msg = paste('variable', p3 ,'is not numeric'))
  # compositional data is not negative
  assert_that(!any(df[[p1]] < 0, na.rm = TRUE),
              msg = paste('variable', p1 ,'contains negative values'))
  assert_that(!any(df[[p2]] < 0, na.rm = TRUE),
              msg = paste('variable', p2 ,'contains negative values'))
  assert_that(!any(df[[p3]] < 0, na.rm = TRUE),
              msg = paste('variable', p3 ,'contains negative values'))
  # NA, Inf, NaN are allowed and are expected to return NA as color

}

#' Validate Shared Parameters
#'
#' Validate parameters shared across tricolore functions.
#'
#' @param pars A named list of parameters.
#'
#' @importFrom assertthat assert_that is.scalar is.flag
#'
#' @keywords internal
ValidateParametersShared <- function (pars) {

  with(pars, {
    # center either NA or three element numeric vector
    # with sum 1 and elements > 0
    assert_that((is.scalar(center) && is.na(center)) ||
                  (length(center) == 3L &&
                     all(is.numeric(center)) &&
                     sum(center) == 1 &&
                     all(center != 0)),
                msg = 'center must be either NA or a three element numeric vector with sum == 1 and all element > 0.')
    # flags
    assert_that(is.flag(legend), is.flag(show_data),
                is.flag(show_center), is.flag(crop))
    # character options
    assert_that(is.scalar(label_as),
                is.character(label_as),
                label_as %in% c('pct', 'pct_diff'),
                msg = 'label_as must be either "pct" or "pct_diff".')
  })

}

#' Validate Tricolore Parameters
#'
#' Validate parameters of Tricolore function.
#'
#' @param pars A named list of parameters.
#'
#' @importFrom assertthat assert_that is.number is.scalar
#'
#' @keywords internal
ValidateParametersTricolore <- function (pars) {

  # a modified version of assertthat::is.count that regards
  # infinite values as counts
  is.count2 <- function (x) {
    if (length(x) != 1) return(FALSE)
    integerish <- is.integer(x) || (is.numeric(x) && (x == trunc(x)))
    if (!integerish) return(FALSE)
    x > 0
  }

  with(pars, {
    # breaks is count scalar > 1 (can't use is.count() because
    # it throws an error when encountering infinite values)
    assert_that(is.scalar(breaks), is.count2(breaks), breaks > 1)
    # hue is numeric scalar in range [0, 1]
    assert_that(is.number(hue), hue >= 0 && hue <= 1)
    # chroma is numeric scalar in range [0, 1]
    assert_that(is.number(chroma), chroma >= 0 && chroma <= 1)
    # lightness is numeric scalar in range [0, 1]
    assert_that(is.number(lightness), lightness >= 0 && lightness <= 1)
    # contrast is numeric scalar in range [0, 1]
    assert_that(is.number(contrast), contrast >= 0 && contrast <= 1)
    # spread is positive numeric scalar
    assert_that(is.number(spread), spread > 0, is.finite(spread))
  })

  ValidateParametersShared(pars)

}

#' Validate TricoloreSextant Parameters
#'
#' Validate parameters of TricoloreSextant function.
#'
#' @param pars A named list of parameters.
#'
#' @importFrom assertthat assert_that is.number is.scalar
#'
#' @keywords internal
ValidateParametersTricoloreSextant <- function (pars) {

  with(pars, {
    assert_that(is.character(values), length(values) == 6)
  })

  ValidateParametersShared(pars)

}

# Compositional Data Analysis ---------------------------------------------

#' Geometric Mean
#'
#' Calculate the geometric mean for a numeric vector.
#'
#' @param x Numeric vector.
#' @param na.rm Should NAs be removed? (default=TRUE)
#' @param zero.rm Should zeros be removed? (default=TRUE)
#'
#' @return The geometric mean as numeric scalar.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' tricolore:::GeometricMean(0:100)
#' tricolore:::GeometricMean(0:100, zero.rm = FALSE)
#'
#' @keywords internal
GeometricMean <- function (x, na.rm = TRUE, zero.rm = TRUE) {
  # the geometric mean can't really deal with elements equal to 0
  # this option removes 0 elements from the vector
  if (zero.rm) { x <- x[x!=0] }
  return(exp(mean(log(x), na.rm = na.rm)))
}

#' Compositional Centre
#'
#' Calculate the centre of a compositional data set.
#'
#' @param P n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.
#'
#' @return The centre of P as an m element numeric vector.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' P <- prop.table(matrix(runif(300), 100), margin = 1)
#' tricolore:::Centre(P)
#'
#' @references
#' Von Eynatten, H., Pawlowsky-Glahn, V., & Egozcue, J. J. (2002).
#' Understanding perturbation on the simplex: A simple method to better
#' visualize and interpret compositional data in ternary diagrams.
#' Mathematical Geology, 34(3), 249-257.
#'
#' Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture
#' Notes on Compositional Data Analysis. Retrieved from
#' https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf
#'
#' @keywords internal
Centre <- function (P) {
  # calculate the geometric mean for each element of the composition
  g <- apply(P, MARGIN = 2, FUN = GeometricMean)
  # the closed vector of geometric means is the mean (centre)
  # of the compositional data set
  return(g/sum(g))
}

#' Compositional Pertubation
#'
#' Pertubate a compositional data set by a compositional vector.
#'
#' @param P n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.
#' @param c Compositional pertubation vector [c1, ..., cm].
#'
#' @return n by m matrix of pertubated compositions.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' P <- prop.table(matrix(runif(12), 4), margin = 1)
#' cP <- tricolore:::Pertube(P, 1/tricolore:::Centre(P))
#' tricolore:::Centre(cP)
#'
#' @references
#' Von Eynatten, H., Pawlowsky-Glahn, V., & Egozcue, J. J. (2002).
#' Understanding perturbation on the simplex: A simple method to better
#' visualize and interpret compositional data in ternary diagrams.
#' Mathematical Geology, 34(3), 249-257.
#'
#' Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture
#' Notes on Compositional Data Analysis. Retrieved from
#' https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf
#'
#' @keywords internal
Pertube <- function (P, c = rep(1/3, 3)) {
  return(prop.table(t(t(P)*c), margin = 1))
}

#' Compositional Powering
#'
#' Raise a compositional data-set to a given power.
#'
#' @param P n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.
#' @param scale Power scalar.
#'
#' @return n by m numeric matrix of powered compositions.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' P <- prop.table(matrix(runif(12), 4), margin = 1)
#' tricolore:::PowerScale(P, 2)
#'
#' @references
#' Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture
#' Notes on Compositional Data Analysis. Retrieved from
#' https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf
#'
#' @keywords internal
PowerScale <- function (P, scale = 1) {
  return(prop.table(P^scale, margin = 1))
}

# Ternary Geometry --------------------------------------------------------

# T(K=k^2):   Equilateral triangle subdivided into K equilateral sub-triangles.
#             Each side of T is divided into k intervals of equal length.
# (p1,p2,p3): Barycentric coordinates wrt. T(K).
# id:         One-dimensional index of sub-triangles in T(K).
#
#                  p2           id index
#                  /\               9
#                 /  \            6 7 8
#                /____\         1 2 3 4 5
#              p1      p3

#' Centroid Coordinates of Sub-Triangles in Segmented Equilateral Triangle
#'
#' Segment an equilateral triangle into k^2 equilateral sub-triangles and return
#' the barycentric centroid coordinates of each sub-triangle.
#'
#' @param k Number of rows in the segmented equilateral triangle.
#'
#' @return A numeric matrix of with index and barycentric centroid coordinates
#'   of regions id=1,...,k^2.
#'
#' @references
#' S. H. Derakhshan and C. V. Deutsch (2009): A Color Scale for Ternary Mixtures.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' tricolore:::TernaryMeshCentroids(1)
#' tricolore:::TernaryMeshCentroids(2)
#' tricolore:::TernaryMeshCentroids(3)
#'
#' @keywords internal
TernaryMeshCentroids <- function (k) {
  # total number of centroids and centroid id
  K = k^2; id = 1:K

  # centroid coordinates as function of K and id
  g <- floor(sqrt(K-id)); gsq <- g^2
  c1 <- (((-K + id + g*(g+2) + 1) %% 2) - 3*gsq - 3*id + 3*K + 1) / (6*k)
  c2 <- -(((-K + gsq + id + 2*g + 1) %% 2) + 3*g - 3*k + 1) / (3*k)
  c3 <- (((-K + gsq + id + 2*g + 1) %% 2) + 3*gsq + 6*g + 3*id - 3*K + 1) / (6*k)

  return(cbind(id = id, p1 = c1, p2 = c2, p3 = c3))
}

#' Vertex Coordinates of Sub-Triangles in Segmented Equilateral Triangle
#'
#' Given the barycentric centroid coordinates of the sub-triangles in an
#' equilateral triangle subdivided into k^2 equilateral sub-triangles, return
#' the barycentric vertex coordinates of each sub-triangle.
#'
#' @param C n by 4 matrix of barycentric centroid coordinates of n=k^2
#'          sub-triangles. Column order: id, p1, p2, p3 with id=1,...,k^2.
#'
#' @return A numeric matrix with index, vertex id and barycentric vertex
#'   coordinates for each of the k^2 sub-triangles.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' k = 2
#' C <- tricolore:::TernaryMeshCentroids(k)
#' tricolore:::TernaryMeshVertices(C)
#'
#' @references
#' S. H. Derakhshan and C. V. Deutsch (2009): A Color Scale for Ternary Mixtures.
#'
#' @keywords internal
TernaryMeshVertices <- function (C) {
  k <- sqrt(nrow(C))
  j <- k - floor(sqrt(k^2-C[,1]))
  i <- C[,1] - (j-1)*(2*k-j+1)
  term1 <- ((-1)^(i %% 2) * 2) / (3*k)
  term2 <- ((-1)^(i %% 2)) / (3*k)

  v1 <- cbind(C[,2] - term1, C[,3] + term2, C[,4] + term2)
  v2 <- cbind(C[,2] + term2, C[,3] - term1, C[,4] + term2)
  v3 <- cbind(C[,2] + term2, C[,3] + term2, C[,4] - term1)

  V <- cbind(C[,1], rep(1:3, each = nrow(C)), rbind(v1, v2, v3))
  colnames(V) <- c('id', 'vertex', 'p1', 'p2', 'p3')

  return(V)
}

#' Distance Between Points in Ternary Coordinates
#'
#' The distances between ternary coordinate p and a set of ternary coordinates C.
#'
#' @param p A vector of ternary coordinates [p1, p2, p3].
#' @param C n by 3 matrix of ternary coordinates [p1, p2, p3](i) for i=1,...,n.
#'
#' @return A numeric vector of distances between coordinate p and all
#'   coordinates in C.
#'
#' @references
#' https://en.wikipedia.org/wiki/Barycentric_coordinate_system#Distance_between_points
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' p <- c(0.5, 0.2, 0.3)
#' C <- prop.table(matrix(runif(3*10), ncol = 3), 1)
#' tricolore:::TernaryDistance(p, C)
#'
#' @keywords internal
TernaryDistance <- function(p, C) {
  Q <- t(p-t(C))
  return(-Q[,2]*Q[,3]-Q[,3]*Q[,1]-Q[,1]*Q[,2])
}

#' For Ternary Coordinates P Return the Nearest Coordinate in Set C
#'
#' @param P,C n by 3 matrix of ternary coordinates [p1, p2, p3](i) for
#'            i=1,...,n. n may be different for P and C.
#'
#' @return n by 3 matrix of ternary coordinates in C.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' P <- prop.table(matrix(runif(9), ncol = 3), 1)
#' C <- tricolore:::TernaryMeshCentroids(2)[,-1]
#' tricolore:::TernaryNearest(P, C)
#'
#' @keywords internal
TernaryNearest <- function (P, C) {
  id <- apply(P, 1, function (x) MaxIndex(-TernaryDistance(x, C)))
  return(C[id,])
}

#' Return Ternary Gridlines Centered Around Some Composition
#'
#' @param center The center of the grid.
#'   A vector of ternary coordinates [p1, p2, p3].
#' @param spacing The spacing of the grid in percent-point increments.
#'   A numeric > 0.
#'
#' @return A list of lists.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' tricolore:::TernaryCenterGrid(c(1/6, 2/6, 3/6), 10)
#'
#' @keywords internal
TernaryCenterGrid <- function (center, spacing) {

  # -1 to 1 by spacing/100 with 0 point
  div_seq <- seq(0, 1, spacing/100)
  div_seq <- c(-rev(div_seq), div_seq[-1])

  # proportion difference from center for all three ternary axes.
  # keep only possible values
  div_seq <- list(
    p1 = div_seq[div_seq >= -center[1] & div_seq <= 1-center[1]],
    p2 = div_seq[div_seq >= -center[2] & div_seq <= 1-center[2]],
    p3 = div_seq[div_seq >= -center[3] & div_seq <= 1-center[3]]
  )

  # percent-point difference from center composition
  labels <- lapply(div_seq, function(x) formatC(x*100, flag = '+'))
  # label center point as percent share
  center_pct <- paste0(formatC(center*100, digits = 1, format = 'f'), '%')
  labels[['p1']][labels[['p1']] == '-0'] <- center_pct[1]
  labels[['p2']][labels[['p2']] == '-0'] <- center_pct[2]
  labels[['p3']][labels[['p3']] == '-0'] <- center_pct[3]


  # breaks in ternary coordinates
  breaks <- list(
    p1 = div_seq[['p1']] + center[1],
    p2 = div_seq[['p2']] + center[2],
    p3 = div_seq[['p3']] + center[3]
  )

  return(list(breaks = breaks, labels = labels))
}

#' Return the Limits of Ternary Coordinates
#'
#' @param P n by 3 matrix of ternary coordinates [p1, p2, p3](i) for
#'          i=1,...,n.
#' @param na.rm Should NAs be removed? (default=TRUE)
#'
#' @return A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' P <- prop.table(matrix(runif(9), ncol = 3), 1)
#' tricolore:::TernaryLimits(P)
#'
#' @keywords internal
TernaryLimits <- function (P, na.rm = TRUE) {
  limits <- matrix(NA, nrow = 2, ncol = 3,
                   dimnames = list(c('lower', 'upper'),
                                   c('p1', 'p2', 'p3')))
  limits[1,] <- apply(P, 2, min, na.rm = na.rm)
  limits[2,] <- c(1 - (limits[1,2] + limits[1,3]),
                  1 - (limits[1,1] + limits[1,3]),
                  1 - (limits[1,1] + limits[1,2]))
  return(limits)
}

#' Vertex Coordinates of Sextants in Equilateral Triangle
#'
#' Given a barycentric center coordinate return the vertex coordinates of the
#' of the sextant regions.
#'
#' @param center The sextant center.
#'   A vector of ternary coordinates [p1, p2, p3].
#'
#' @return Index, vertex id and barycentric vertex coordinates for each of the
#'         6 sextants.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' tricolore:::TernarySextantVertices(rep(1/3, 3))
#'
#' @keywords internal
TernarySextantVertices <- function (center) {

  # define corner points
  p1 = c(1, 0, 0); p2 = c(0, 1, 0); p3 = c(0, 0, 1)
  a1 <- c(center[1], 1-center[1], 0); a2 <- c(center[1], 0, 1-center[1])
  b1 <- c(0, center[2], 1-center[2]); b2 <- c(1-center[2], center[2], 0)
  c1 <- c(1-center[3], 0, center[3]); c2 <- c(0, 1-center[3], center[3])

  # ternary sextant vertices
  V <- cbind(
    id =
      c(rep(1, 5), rep(2, 4),
        rep(3, 5), rep(4, 4),
        rep(5, 5), rep(6, 4)),
    vertex = rep(c(1:5, 1:4), 3),
    matrix(
      c(center, c1, p1, b2, center, # 1
        center, b2, a1, center,     # 2
        center, a1, p2, c2, center, # 3
        center, c2, b1, center,     # 4
        center, b1, p3, a2, center, # 5
        center, a2, c1, center),    # 6
      ncol = 3, nrow = 27, byrow = TRUE,
      dimnames = list(NULL, c('p1', 'p2', 'p3'))
    )
  )

  return(V)

}

#' Return Surrounding Sextant of Barycentric Coordinates
#'
#' Given barycentric coordinates return the id of the surrounding sextant.
#'
#' @param P n by 3 matrix of ternary coordinates [p1, p2, p3](i) for
#'          i=1,...,n.
#' @param center The sextant center.
#'   A vector of ternary coordinates [p1, p2, p3].
#'
#' @return An n element character vector of sextant id's 1 to 6.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' P <- prop.table(matrix(runif(9), ncol = 3), 1)
#' tricolore:::TernarySurroundingSextant(P, rep(1/3, 3))
#'
#' @keywords internal
TernarySurroundingSextant <- function (P, center) {
  # six cases, six sextants, NA if at center or NA in input
  is_larger <- t(t(P) > center)
  id <- apply(is_larger, 1, function (x) {
    y <- NA
    if (identical(x, c(TRUE, FALSE, FALSE))) y <- 1
    if (identical(x, c(TRUE, TRUE, FALSE)))  y <- 2
    if (identical(x, c(FALSE, TRUE, FALSE))) y <- 3
    if (identical(x, c(FALSE, TRUE, TRUE)))  y <- 4
    if (identical(x, c(FALSE, FALSE, TRUE))) y <- 5
    if (identical(x, c(TRUE, FALSE, TRUE)))  y <- 6
    y
  })
  return(id)
}

# Ternary Color Maps ------------------------------------------------------

#' CIE-Lch Mixture of Ternary Composition
#'
#' Return the ternary balance scheme colors for a matrix of ternary compositions.
#'
#' @param P n by 3 matrix of ternary compositions [p1, p2, p3](i) for
#'          i=1, ..., n.
#' @param center Ternary coordinates of the grey-point.
#' @param breaks Number of breaks in the discrete color scale. An integer >1.
#'               Values above 99 imply no discretization.
#' @param h_ Primary hue of the first ternary element in angular degrees [0, 360].
#' @param c_ Maximum possible chroma of mixed colors [0, 200].
#' @param l_ Lightness of mixed colors [0, 100].
#' @param contrast Lightness contrast of the color scale [0, 1).
#' @param spread Spread of the color scale around center > 0.
#'
#' @return An n row data frame giving, for each row of the input P, the input
#' proportions [p1, p2, p3], parameters of the color mixture (h, c, l) and the
#' hex-rgb string of the mixed colors (rgb).
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' P <- prop.table(matrix(runif(9), ncol = 3), 1)
#' tricolore:::ColorMapTricolore(P, center = rep(1/3, 3), breaks = 4,
#'                               h_ = 80, c_ = 140, l_ = 80,
#'                               contrast = 0.4, spread = 1)
#'
#' @importFrom grDevices hcl hsv
#'
#' @keywords internal
ColorMapTricolore <- function (P, center, breaks, h_, c_, l_, contrast, spread) {

  ### Discretize ###

  # closing (copy of closed, non-transformed input data for output)
  P <- P_notrans <- prop.table(P, margin = 1)

  # discretize to nearest ternary mesh centroid
  # don't discretize if breaks > 99 to avoid expensive calculations
  # which don't make much of a difference in output
  if (breaks < 100) {
    P <- TernaryNearest(P, TernaryMeshCentroids(breaks)[,-1])
  }

  ### Center and scale ###

  # centering
  P <- Pertube(P, 1/center)
  # scaling
  P <- PowerScale(P, spread)

  ### Colorize ###

  # calculate the chroma matrix C by scaling the row proportions
  # of the input matrix P by the maximum chroma parameter.
  C <- P*c_

  # generate primary colors starting with a hue value in [0, 360) and then
  # picking two equidistant points on the circumference of the color wheel.
  # input hue in degrees, all further calculations in radians.
  phi <- (h_*0.0174 + c(0, 2.09, 4.19)) %% 6.28

  # the complex matrix Z represents each case (i) and group (j=1,2,3) specific
  # color in complex polar form with hue as angle and chroma as radius.
  Z <- matrix(complex(argument = phi, modulus = c(t(C))),
              ncol = 3, byrow = TRUE)

  # adding up the rows gives the CIE-Lab (cartesian) coordinates
  # of the convex color mixture in complex form.
  z <- rowSums(Z)
  # convert the cartesian CIE-Lab coordinates to polar CIE-Luv coordinates
  # and add lightness level.
  M <- cbind(h = (Arg(z)*57.3)%%360, c = Mod(z), l = l_)

  # decrease lightness and chroma towards the center of the color scale
  cfactor <- M[,2]*contrast/c_ + 1-contrast
  M[,3] <- cfactor*M[,3]
  M[,2] <- cfactor*M[,2]

  # convert the complex representation of the color mixture to
  # hex-srgb representation via the hcl (CIE-Luv) color space
  rgb <- hcl(h = M[,1], c = M[,2], l = M[,3],
             alpha = 1, fixup = TRUE)
  # remove alpha information
  rgb <- substr(rgb, 1, 7)

  ### Output ###

  # non-transformed compositions, hcl values of mixtures and rgb code
  result <- data.frame(P_notrans, M[,1], M[,2], M[,3], rgb,
                       row.names = NULL, check.rows = FALSE,
                       check.names = FALSE, stringsAsFactors = FALSE)
  colnames(result) <- c('p1', 'p2', 'p3', 'h', 'c', 'l', 'rgb')
  return(result)
}

#' Sextant Encoding of Ternary Composition
#'
#' Return the sextant scheme colors for a matrix of ternary compositions.
#'
#' @param P n by 3 matrix of ternary compositions [p1, p2, p3](i) for
#'          i=1, ..., n.
#' @param center Ternary coordinates of the sextant meeting point.
#' @param values 6 element character vector of rgb-codes.
#'
#' @return An n row data frame giving, for each row of the input P, the input
#' proportions [p1, p2, p3], sextant id (sextant) and the hex-rgb string of the
#' mixed colors (rgb).
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' P <- prop.table(matrix(runif(9), ncol = 3), 1)
#' tricolore:::ColorMapSextant(P, c(1/3, 1/3, 1/3),
#'                             c('#01A0C6', '#B8B3D8', '#F11D8C', '#FFB3B3',
#'                               '#FFFF00', '#B3DCC3'))
#' @keywords internal
ColorMapSextant <- function (P, center, values) {
  # close composition
  P <- prop.table(P, margin = 1)

  # assign points to sextants and corresponding color codes
  sextant <- TernarySurroundingSextant(P, center)
  rgb <- values[sextant]

  # non-transformed compositions, sextant id and hexsrgb code
  result <- data.frame(P, sextant, rgb,
                       row.names = NULL, check.rows = FALSE,
                       check.names = FALSE, stringsAsFactors = FALSE)
  colnames(result) <- c('p1', 'p2', 'p3', 'sextant', 'rgb')
  return(result)
}

# Ternary Color Keys ------------------------------------------------------

#' Breaks and Labels for Ternary Color Key
#'
#' Return various types of breaks and labels for ternary color keys.
#'
#' @param type   An integer 1, 2, or 3.
#' @param center Ternary coordinates of the grey-point.
#' @param breaks Number of breaks in the discrete color scale. An integer >1.
#'               Values above 99 imply no discretization.
#'
#' @return A list of lists containing breaks and labels for each of the 3
#'   ternary axes.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' tricolore:::BreaksAndLabels(1, breaks = 3)
#' tricolore:::BreaksAndLabels(2)
#' tricolore:::BreaksAndLabels(3, center = c(1/3, 1/3, 1/3))
#'
#' @keywords internal
BreaksAndLabels <- function (type, center = NULL, breaks = NULL) {
  brk_lab <-
    switch(type,
           list(breaks = list(p1 = seq(0, 1, length.out = breaks+1),
                              p2 = seq(0, 1, length.out = breaks+1),
                              p3 = seq(0, 1, length.out = breaks+1)),
                labels = list(p1 = round(seq(0, 1, length.out = breaks+1)*100, 1),
                              p2 = round(seq(0, 1, length.out = breaks+1)*100, 1),
                              p3 = round(seq(0, 1, length.out = breaks+1)*100, 1))),
           list(breaks = list(p1 = c(0.25, 0.5, 0.75),
                              p2 = c(0.25, 0.5, 0.75),
                              p3 = c(0.25, 0.5, 0.75)),
                labels = list(p1 = c('25', '50', '75'),
                              p2 = c('25', '50', '75'),
                              p3 = c('25', '50', '75'))),
           TernaryCenterGrid(center = center, spacing = 10)
    )
  return(brk_lab)
}

#' Template for Ternary Key
#'
#' Return various types of breaks and labels for ternary color keys.
#'
#' @param legend_surface A data frame with numeric 'id', 'p1', 'p2', 'p3' and
#'                       character column 'rgb'.
#' @param limits A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.
#' @param brklab Breaks and labels as returned by \code{\link{BreaksAndLabels}}.
#' @param show_center Should the center be marked on the legend? (logical)
#' @param center Ternary coordinates of the grey-point.
#' @param lwd A numeric scalar giving the linewidth of the legend surface
#'            polygons.
#'
#' @return A ggtern grob.
#'
#' @importFrom ggplot2 scale_color_identity
#'   scale_fill_identity element_text theme layer
#' @importFrom ggtern ggtern aes geom_mask
#'   scale_L_continuous scale_R_continuous scale_T_continuous
#'   geom_Lline geom_Tline geom_Rline theme_classic
#' @importFrom rlang .data
#'
#' @keywords internal
BasicKey <- function(legend_surface, limits, brklab, show_center, center, lwd) {

  key <-
    # basic legend
    ggtern(legend_surface) +
    layer(
      geom = 'polygon', stat = 'identity', position = 'identity',
      mapping = aes(
        x = .data[['p1']], y = .data[['p2']], z = .data[['p3']],
        group = .data[['id']], fill = .data[['rgb']], color = .data[['rgb']]
      ),
      params = list(lwd = lwd),
      check.aes = FALSE, check.param = FALSE
    ) +
    geom_mask() +
    # rgb color input
    scale_color_identity(guide = 'none') +
    scale_fill_identity(guide = 'none') +
    # theme
    theme_classic() +
    theme(tern.axis.title.L = element_text(hjust = 0.2, vjust = 1, angle = -60),
          tern.axis.title.R = element_text(hjust = 0.8, vjust = 0.6, angle = 60)) +
    # grid and labels
    list(
      list(
        scale_L_continuous(
          limits = limits[,1],
          breaks = brklab[['breaks']][['p1']],
          labels = brklab[['labels']][['p1']]
        ),
        scale_T_continuous(
          limits = limits[,2],
          breaks = brklab[['breaks']][['p2']],
          labels = brklab[['labels']][['p2']]
        ),
        scale_R_continuous(
          limits = limits[,3],
          breaks = brklab[['breaks']][['p3']],
          labels = brklab[['labels']][['p3']]
        )
      ),
      if (show_center) {
        list(
          geom_Lline(Lintercept = center[1], color = 'black', alpha = 0.5),
          geom_Tline(Tintercept = center[2], color = 'black', alpha = 0.5),
          geom_Rline(Rintercept = center[3], color = 'black', alpha = 0.5)
        )
      }
    )

  return(key)

}

#' Ternary Balance Scheme Legend
#'
#' Plot a ternary balance scheme legend.
#'
#' @inheritParams ColorMapTricolore
#' @param label_as "pct" for percent-share labels or "pct_diff" for
#'   percent-point-difference from center labels.
#' @param show_center Should the center be marked on the legend? (logical)
#' @param limits A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.
#'
#' @return A ggtern grob.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' tricolore:::ColorKeyTricolore(center = rep(1/3, 3), breaks = 4,
#'                               h_ = 80, c_ = 140, l_ = 80,
#'                               contrast = 0.4, spread = 1,
#'                               label_as = "pct", show_center = FALSE)
#'
#' @keywords internal
ColorKeyTricolore <- function (center, breaks, h_, c_, l_, contrast, spread,
                               label_as, show_center,
                               limits = matrix(0:1, nrow = 2, ncol = 3)) {

  ### Create and colorize legend surface ###

  # don't allow more than 99^2 different colors/regions in the legend
  if (breaks > 99) { breaks = 100 }

  # calculate ternary vertex coordinates and
  # fill color for each sub-triangle
  C <- TernaryMeshCentroids(breaks)
  V <- TernaryMeshVertices(C)
  rgb <- ColorMapTricolore(P = C[,-1], center, breaks = 100, h_, c_, l_,
                           contrast, spread)[['rgb']]

  legend_surface <- data.frame(V, rgb = rep(rgb, 3),
                               row.names = NULL, check.rows = FALSE,
                               check.names = FALSE, stringsAsFactors = FALSE)

  ### Breaks and labels ###

  if (label_as == 'pct' && breaks <= 10) {
    brklab <- BreaksAndLabels(1, center, breaks)
  }
  if (label_as == 'pct' && breaks > 10) {
    brklab <- BreaksAndLabels(2, center, breaks)
  }
  if (label_as == 'pct_diff') {
    brklab <- BreaksAndLabels(3, center, breaks)
  }

  ### Plot key ###

  return(BasicKey(legend_surface, limits, brklab, show_center, center, lwd = 1))

}

#' Sextant Scheme Legend
#'
#' Plot a sextant scheme legend.
#'
#' @inheritParams ColorMapSextant
#' @param label_as "pct" for percent-share labels or "pct_diff" for
#'   percent-point-difference from center labels.
#' @param show_center Should the center be marked on the legend? (logical)
#' @param limits A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.
#'
#' @return A ggtern grob.
#'
#' @examples
#' # NOTE: only intended for internal use and not part of the API
#' tricolore:::ColorKeySextant(center = prop.table(runif(3)),
#'                             values = c('#01A0C6', '#B8B3D8', '#F11D8C',
#'                                        '#FFB3B3', '#FFFF00', '#B3DCC3'),
#'                             label_as = 'pct_diff', show_center = TRUE)
#'
#' @keywords internal
ColorKeySextant <- function (center, values, label_as, show_center,
                             limits = matrix(0:1, nrow = 2, ncol = 3)) {

  ### Create and colorize legend surface ###

  # calculate ternary vertex coordinates and
  # fill color for each sub-triangle
  V <- TernarySextantVertices(center)
  rgb <- rep(values, c(5, 4, 5, 4, 5, 4))

  legend_surface <- data.frame(V, rgb = rgb,
                               row.names = NULL, check.rows = FALSE,
                               check.names = FALSE, stringsAsFactors = FALSE)

  ### Breaks and labels ###

  if (label_as == 'pct') {
    brklab <- BreaksAndLabels(2, center)
  }
  if (label_as == 'pct_diff') {
    brklab <- BreaksAndLabels(3, center)
  }

  ### Plot key ###

  return(BasicKey(legend_surface, limits, brklab, show_center, center, lwd = 0))

}

# User functions ----------------------------------------------------------

#' Ternary Balance Color Scale
#'
#' Color-code three-part compositions with a ternary balance color scale and
#' return a color key.
#'
#' @param df Data frame of compositional data.
#' @param p1 Column name for variable in df giving first proportion
#'           of ternary composition (string).
#' @param p2 Column name for variable in df giving second proportion
#'           of ternary composition (string).
#' @param p3 Column name for variable in df giving third proportion
#'           of ternary composition (string).
#' @param center Ternary coordinates of the color scale center.
#'               (default = 1/3,1/3,1/3). NA puts center over the compositional
#'               mean of the data.
#' @param breaks Number of per-axis breaks in the discrete color scale.
#'               An integer >1. Values above 99 imply no discretization.
#' @param hue Primary hue of the first ternary element (0 to 1).
#' @param chroma Maximum possible chroma of mixed colors (0 to 1).
#' @param lightness Lightness of mixed colors (0 to 1).
#' @param contrast Lightness contrast of the color scale (0 to 1).
#' @param spread The spread of the color scale. Choose values > 1 to focus the
#'               color scale on the center.
#' @param legend Should a legend be returned along with the colors? (default=TRUE)
#' @param show_data Should the data be shown on the legend? (default=TRUE)
#' @param show_center Should the center be shown on the legend?
#'   (default=FALSE if center is at c(1/3, 1/3, 1/3), otherwise TRUE)
#' @param label_as "pct" for percent-share labels or "pct_diff" for
#'   percent-point-difference from center labels.
#'   (default='pct' if center is at c(1/3, 1/3, 1/3), otherwise 'pct_diff')
#' @param crop Should the legend be cropped to the data? (default=FALSE)
#' @param input_validation Should the function arguments be validated? (default=TRUE)
#'
#' @return
#' * legend=FALSE: A vector of rgbs hex-codes representing the ternary balance
#'                 scheme colors.
#' * legend=TRUE: A list with elements "rgb" and "key".
#'
#' @examples
#' P <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))
#' Tricolore(P, 'V1', 'V2', 'V3')
#'
#' @importFrom ggplot2 labs layer
#' @importFrom ggtern aes
#' @importFrom rlang .data
#'
#' @md
#'
#' @export
Tricolore <- function (df, p1, p2, p3,
                       center = rep(1/3, 3),
                       breaks = ifelse(identical(center, rep(1/3, 3)), 4, Inf),
                       hue = 0.2, chroma = 0.7, lightness = 0.8,
                       contrast = 0.4, spread = 1,
                       legend = TRUE, show_data = TRUE,
                       show_center = ifelse(identical(center, rep(1/3, 3)),
                                            FALSE, TRUE),
                       label_as = ifelse(identical(center, rep(1/3, 3)),
                                         'pct', 'pct_diff'),
                       crop = FALSE, input_validation = TRUE) {

  # validation of main input arguments
  if (input_validation) {
    ValidateMainArguments(df, p1, p2, p3)
    ValidateParametersTricolore(
      list(breaks = breaks, hue = hue, chroma = chroma,
           lightness = lightness, contrast = contrast,
           center = center, spread = spread, legend = legend,
           show_data = show_data, show_center = show_center,
           label_as = label_as, crop = crop)
    )
  }

  # construct 3 column matrix of proportions
  P <- cbind(df[[p1]], df[[p2]], df[[p3]])
  # ensure data is closed
  P <- prop.table(P, 1)

  # center color-scale over data's centre if center==NA
  if ( is.na(center[1]) ) { center = Centre(P) }

  # derive the color mixture
  # the magic numbers rescale the [0,1] color-specification to the
  # cylindrical-coordinates format required by ColorMapTricolore()
  mixture <- ColorMapTricolore(P, center, breaks,
                               hue*360, chroma*200, lightness*100,
                               contrast, spread)

  # if specified, return a legend along with the srgb color mixtures...
  if (legend) {

    # crop legend to to data range if crop==TRUE
    if (crop) {
      limits <- TernaryLimits(P, na.rm = TRUE)
      # else use full range
    } else {
      limits <- matrix(0:1, nrow = 2, ncol = 3)
    }

    key <-
      ColorKeyTricolore(center, breaks, hue*360, chroma*200, lightness*100,
                        contrast, spread, label_as, show_center, limits) +
      list(
        # labels take names from input variables
        labs(x = p1, y = p2, z = p3),
        if (show_data) {
          layer(
            geom = 'point', stat = 'identity', position = 'identity',
            mapping = aes(x = .data[['p1']], y = .data[['p2']], z = .data[['p3']]),
            params = list(color = 'black', shape = 16, size = 0.5, alpha = 0.5),
            data = mixture,
            check.aes = FALSE, check.param = FALSE
          )
        }
      )

    result <- list(rgb = mixture[['rgb']], key = key)
    # ... else just return a vector of hexsrgb codes of the mixed colors
  } else {
    result <- mixture[['rgb']]
  }

  return(result)
}


#' Ternary Sextant Color Scale
#'
#' Color-code three-part compositions with a ternary sextant color scale and
#' return a color key.
#'
#' @param df Data frame of compositional data.
#' @param p1 Column name for variable in df giving first proportion
#'           of ternary composition (string).
#' @param p2 Column name for variable in df giving second proportion
#'           of ternary composition (string).
#' @param p3 Column name for variable in df giving third proportion
#'           of ternary composition (string).
#' @param center Ternary coordinates of the color scale center.
#'               (default = 1/3,1/3,1/3). NA puts center over the compositional
#'               mean of the data.
#' @param values 6 element character vector of rgb-codes.
#' @param legend Should a legend be returned along with the colors? (default=TRUE)
#' @param show_data Should the data be shown on the legend? (default=TRUE)
#' @param show_center Should the center be shown on the legend?
#' (default=FALSE if center is at c(1/3, 1/3, 1/3), otherwise TRUE)
#' @param label_as "pct" for percent-share labels or "pct_diff" for
#'   percent-point-difference from center labels.
#'   (default='pct' if center is at c(1/3, 1/3, 1/3), otherwise 'pct_diff')
#' @param crop Should the legend be cropped to the data? (default=FALSE)
#' @param input_validation Should the function arguments be validated? (default=TRUE)
#'
#' @return
#' * legend=FALSE: A vector of rgbs hex-codes representing the ternary balance
#'                 scheme colors.
#' * legend=TRUE: A list with elements "rgb" and "key".
#'
#' @examples
#' P <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))
#' TricoloreSextant(P, 'V1', 'V2', 'V3')
#'
#' @importFrom ggplot2 labs layer
#' @importFrom ggtern aes
#' @importFrom rlang .data
#'
#' @md
#'
#' @export
TricoloreSextant <- function (df, p1, p2, p3,
                              center = rep(1/3, 3),
                              values = c("#FFFF00", "#B3DCC3", "#01A0C6",
                                         "#B8B3D8", "#F11D8C", "#FFB3B3"),
                              legend = TRUE, show_data = TRUE, show_center = TRUE,
                              label_as = ifelse(identical(center, rep(1/3, 3)),
                                                'pct', 'pct_diff'),
                              crop = FALSE, input_validation = TRUE) {

  # validation of main input arguments
  if (input_validation) {
    ValidateMainArguments(df, p1, p2, p3)
    ValidateParametersTricoloreSextant(
      list(values = values,
           center = center,
           legend = legend,
           show_data = show_data,
           show_center = show_center,
           label_as = label_as,
           crop = crop)
    )
  }

  # construct 3 column matrix of proportions
  P <- cbind(df[[p1]], df[[p2]], df[[p3]])
  # ensure data is closed
  P <- prop.table(P, 1)

  # center color-scale over data's centre if center==NA
  if ( is.na(center[1]) ) { center = Centre(P) }

  # derive the color mixture
  mixture <- ColorMapSextant(P, center, values)

  # if specified, return a legend along with the srgb color mixtures...
  if (legend) {

    # crop legend to to data range if crop==TRUE
    if (crop) {
      limits <- TernaryLimits(P, na.rm = TRUE)
      # else use full range
    } else {
      limits <- matrix(0:1, nrow = 2, ncol = 3)
    }

    key <-
      ColorKeySextant(center, values, label_as, show_center, limits) +
      list(
        # labels take names from input variables
        labs(x = p1, y = p2, z = p3),
        if (show_data) {
          layer(
            geom = 'point', stat = 'identity', position = 'identity',
            mapping = aes(x = .data[['p1']], y = .data[['p2']], z = .data[['p3']]),
            params = list(color = 'black', shape = 16, size = 0.5, alpha = 0.5),
            data = mixture,
            check.aes = FALSE, check.param = FALSE
          )
        }
      )

    result <- list(rgb = mixture[['rgb']], key = key)
    # ... else just return a vector of hexsrgb codes of the mixed colors
  } else {
    result <- mixture[['rgb']]
  }

  return(result)

}

#' Interactive Tricolore Demonstration
#'
#' An interactive demonstration of the tricolore color scale inspired by the
#' colorbrewer2.org application. Helps in picking the right color scale for your
#' data.
#'
#' @return Opens a shiny app session.
#'
#' @export
DemoTricolore <- function () {
  app_dir <- system.file('shiny', package = 'tricolore')
  if (app_dir == '') {
    stop("Could not find example directory. Try re-installing 'tricolore'.",
         call. = FALSE)
  }
  shiny::runApp(app_dir, display.mode = 'normal')
}

# Data --------------------------------------------------------------------

#' Flat Map of European Continent
#'
#' A ggplot object rendering a flat background map of the European continent.
#'
#' @source
#'   Derived from geodata provided by the Natural Earth project.
#'   \url{https://www.naturalearthdata.com/}
'euro_basemap'

#' NUTS-2 Level Geodata and Compositional Data for Europe
#'
#' A simple-features dataframe containing the NUTS-2 level polygons of European
#' regions along with regional compositional data on education and labor-force.
#'
#' @format
#'   A data frame with 312 rows and 9 variables:
#'   \describe{
#'     \item{id}{NUTS-2 code.}
#'     \item{name}{Name of NUTS-2 region.}
#'     \item{ed_0to2}{Share of population with highest attained education "lower secondary or less".}
#'     \item{ed_3to4}{Share of population with highest attained education "upper secondary".}
#'     \item{ed_5to8}{Share of population with highest attained education "tertiary".}
#'     \item{lf_pri}{Share of labor-force in primary sector.}
#'     \item{lf_sec}{Share of labor-force in secondary sector.}
#'     \item{lf_ter}{Share of labor-force in tertiary sector.}
#'     \item{geometry}{Polygon outlines for regions in sf package format.}
#'   }
#'
#' @details
#'   Variables starting with "ed" refer to the relative share of population ages
#'   25 to 64 by educational attainment in the European NUTS-2 regions 2016.
#'
#'   Variables starting with "lf" refer to the relative share of workers by
#'   labor-force sector in the European NUTS-2 regions 2016. The original NACE
#'   (rev. 2) codes have been recoded into the three sectors "primary" (A),
#'   "secondary" (B-E & F) and "tertiary" (all other NACE codes).
#'
#' @source
#'   Derived from Eurostats European Geodata.
#'   (c) EuroGeographics for the administrative boundaries.
#'   \url{https://gisco-services.ec.europa.eu/distribution/v2/nuts/nuts-2016-files.html}
#'
#'   Education data derived from Eurostats table "edat_lfse_04".
#'
#'   Labor-force data derived from Eurostats table "lfst_r_lfe2en2".
'euro_example'


================================================
FILE: R/zzz.R
================================================
.onAttach <- function(...) {

  packageStartupMessage('Please cite tricolore. See citation("tricolore").')

}


================================================
FILE: README.Rmd
================================================
---
title: "tricolore. A flexible color scale for ternary compositions"
output: github_document
---

```{r echo=FALSE}
knitr::opts_chunk$set(warning=FALSE,
                      message=FALSE,
                      fig.width = 12,
                      fig.height = 12)
```

Jonas 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/) ·
Ilya 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)

[![CRAN_Version](https://www.r-pkg.org/badges/version/tricolore)](https://cran.r-project.org/package=tricolore)
![GitHub Actions R-CMD-check](https://github.com/jschoeley/tricolore/actions/workflows/R-CMD-check.yaml/badge.svg)
[![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)

What is *tricolore*?
--------------------

`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

- *discrete* and *continuous* color support,
- support for unbalanced compositional data via *centering*,
- support for data with very narrow range via *scaling*,
- *hue*, *chroma* and *lightness* options.

![](README_files/teaser.png)

Getting Started
---------------

```{r eval=FALSE}
install.packages('tricolore')
library(tricolore); DemoTricolore()
```

The `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.

Here's a minimal example using simulated data.

```{r message=FALSE, fig.cap='A ternary color key with the color-coded compositional data visible as points.'}
library(tricolore)

# simulate 243 ternary compositions
P <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))
# color-code each composition and return a corresponding color key
colors_and_legend <- Tricolore(P, 'V1', 'V2', 'V3')
# the color-coded compositions
head(colors_and_legend$rgb)
colors_and_legend$key
```

You can familiarize yourself with the various options of `tricolore` by running `DemoTricolore()`.

Ternary choropleth maps
-----------------------

Here I demonstrate how to create a choropleth map of the regional distribution of education attainment in Europe 2016 using `ggplot2`.

The 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.

**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.**

```{r}
# color-code the data set and generate a color-key
tric_educ <- Tricolore(euro_example,
                       p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8')
```

`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.

```{r}
# add the vector of colors to the `euro_example` data
euro_example$educ_rgb <- tric_educ$rgb
```

**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.**

The 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`.

```{r}
library(ggplot2)

plot_educ <-
  # using data sf data `euro_example`...
  ggplot(euro_example) +
  # ...draw a choropleth map
  geom_sf(aes(fill = educ_rgb, geometry = geometry), size = 0.1) +
  # ...and color each region according to the color-code
  # in the variable `educ_rgb`
  scale_fill_identity()

plot_educ
```

Using `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.

```{r}
library(ggtern)
plot_educ +
  annotation_custom(
    ggplotGrob(tric_educ$key),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  )
```

Because the color key behaves just like a `ggplot2` plot we can change it to our liking.

```{r}
plot_educ <-
  plot_educ +
  annotation_custom(
    ggplotGrob(
      tric_educ$key +
        labs(L = '0-2', T = '3-4', R = '5-8')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  )
plot_educ
```

Some final touches...

```{r}
plot_educ +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in educational attainment',
       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')
```

Continuous vs. discrete colors
------------------------------

By 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...

```{r}
# color-code the data set and generate a color-key
tric_educ_disc <- Tricolore(euro_example,
                            p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',
                            breaks = Inf)
euro_example$educ_rgb_disc <- tric_educ_disc$rgb

ggplot(euro_example) +
  geom_sf(aes(fill = educ_rgb_disc, geometry = geometry), size = 0.1) +
  scale_fill_identity() +
  annotation_custom(
    ggplotGrob(
      tric_educ_disc$key +
        labs(L = '0-2', T = '3-4', R = '5-8')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  ) +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in educational attainment',
       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')
```

...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.

```{r}
# color-code the data set and generate a color-key
tric_educ_disc <- Tricolore(euro_example,
                            p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',
                            breaks = 2)
euro_example$educ_rgb_disc <- tric_educ_disc$rgb

ggplot(euro_example) +
  geom_sf(aes(fill = educ_rgb_disc, geometry = geometry), size = 0.1) +
  scale_fill_identity() +
  annotation_custom(
    ggplotGrob(
      tric_educ_disc$key +
        labs(L = '0-2', T = '3-4', R = '5-8')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  ) +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in educational attainment',
       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')
```

Ternary centering
-----------------

While 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.

```{r}
tric_lf_non_centered <- Tricolore(euro_example, breaks = Inf,
                                  'lf_pri', 'lf_sec', 'lf_ter')

euro_example$rgb_lf_non_centered <- tric_lf_non_centered$rgb

ggplot(euro_example) +
  geom_sf(aes(fill = rgb_lf_non_centered, geometry = geometry), size = 0.1) +
  scale_fill_identity() +
  annotation_custom(
    ggplotGrob(tric_lf_non_centered$key +
                 labs(L = '% Primary', T = '% Secondary', R = '% Tertiary')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  ) +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in labor force composition',
       subtitle = 'Regional distribution of labor force across the three sectors in 2016.')

```

A 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.

Centering 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.

```{r}
tric_lf_centered <-
  Tricolore(euro_example,
            'lf_pri', 'lf_sec', 'lf_ter',
            center = NA, crop = FALSE)

euro_example$rgb_lf_centered <- tric_lf_centered$rgb

ggplot(euro_example) +
  geom_sf(aes(fill = rgb_lf_centered, geometry = geometry), size = 0.1) +
  scale_fill_identity() +
  annotation_custom(
    ggplotGrob(
      tric_lf_centered$key +
        labs(L = '% Primary', T = '% Secondary', R = '% Tertiary')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  ) +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in labor force composition',
       subtitle = 'Regional distribution of labor force across the three sectors in 2016.')
```

Contributing
------------

This software is an academic project. We welcome any issues and pull requests.

Please report any bugs you find by submitting an issue on github.com/jschoeley/tricolore/issues.

If 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).


================================================
FILE: README.md
================================================
<img src="inst/figures/tricolore.png" align="right" width="150" height="174" />tricolore. A flexible color scale for ternary compositions
================

Jonas 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/) · Ilya 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)

[![CRAN_Version](https://www.r-pkg.org/badges/version/tricolore)](https://cran.r-project.org/package=tricolore)
![GitHub Actions
R-CMD-check](https://github.com/jschoeley/tricolore/actions/workflows/R-CMD-check.yaml/badge.svg)
[![License: GPL
v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)

## What is *tricolore*?

`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

- *discrete* and *continuous* color support,
- support for unbalanced compositional data via *centering*,
- support for data with very narrow range via *scaling*,
- *hue*, *chroma* and *lightness* options.

![](README_files/teaser.png)

## Getting Started

``` r
install.packages('tricolore')
library(tricolore); DemoTricolore()
```

The `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.

Here’s a minimal example using simulated data.

``` r
library(tricolore)

# simulate 243 ternary compositions
P <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))
# color-code each composition and return a corresponding color key
colors_and_legend <- Tricolore(P, 'V1', 'V2', 'V3')
# the color-coded compositions
head(colors_and_legend$rgb)
```

    ## [1] "#727272" "#4AA0BB" "#6E8E72" "#BC8C67" "#37A789" "#A48AC6"

``` r
colors_and_legend$key
```

<figure>
<img src="README_files/figure-gfm/unnamed-chunk-3-1.png"
alt="A ternary color key with the color-coded compositional data visible as points." />
<figcaption aria-hidden="true">A ternary color key with the color-coded
compositional data visible as points.</figcaption>
</figure>

You can familiarize yourself with the various options of `tricolore` by
running `DemoTricolore()`.

## Ternary choropleth maps

Here I demonstrate how to create a choropleth map of the regional
distribution of education attainment in Europe 2016 using `ggplot2`.

The 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.

**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.**

``` r
# color-code the data set and generate a color-key
tric_educ <- Tricolore(euro_example,
                       p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8')
```

`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.

``` r
# add the vector of colors to the `euro_example` data
euro_example$educ_rgb <- tric_educ$rgb
```

**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.**

The 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`.

``` r
library(ggplot2)

plot_educ <-
  # using data sf data `euro_example`...
  ggplot(euro_example) +
  # ...draw a choropleth map
  geom_sf(aes(fill = educ_rgb, geometry = geometry), size = 0.1) +
  # ...and color each region according to the color-code
  # in the variable `educ_rgb`
  scale_fill_identity()

plot_educ
```

![](README_files/figure-gfm/unnamed-chunk-6-1.png)<!-- -->

Using `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.

``` r
library(ggtern)
plot_educ +
  annotation_custom(
    ggplotGrob(tric_educ$key),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  )
```

![](README_files/figure-gfm/unnamed-chunk-7-1.png)<!-- -->

Because the color key behaves just like a `ggplot2` plot we can change
it to our liking.

``` r
plot_educ <-
  plot_educ +
  annotation_custom(
    ggplotGrob(
      tric_educ$key +
        labs(L = '0-2', T = '3-4', R = '5-8')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  )
plot_educ
```

![](README_files/figure-gfm/unnamed-chunk-8-1.png)<!-- -->

Some final touches…

``` r
plot_educ +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in educational attainment',
       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')
```

![](README_files/figure-gfm/unnamed-chunk-9-1.png)<!-- -->

## Continuous vs. discrete colors

By 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…

``` r
# color-code the data set and generate a color-key
tric_educ_disc <- Tricolore(euro_example,
                            p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',
                            breaks = Inf)
euro_example$educ_rgb_disc <- tric_educ_disc$rgb

ggplot(euro_example) +
  geom_sf(aes(fill = educ_rgb_disc, geometry = geometry), size = 0.1) +
  scale_fill_identity() +
  annotation_custom(
    ggplotGrob(
      tric_educ_disc$key +
        labs(L = '0-2', T = '3-4', R = '5-8')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  ) +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in educational attainment',
       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')
```

![](README_files/figure-gfm/unnamed-chunk-10-1.png)<!-- -->

…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.

``` r
# color-code the data set and generate a color-key
tric_educ_disc <- Tricolore(euro_example,
                            p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',
                            breaks = 2)
euro_example$educ_rgb_disc <- tric_educ_disc$rgb

ggplot(euro_example) +
  geom_sf(aes(fill = educ_rgb_disc, geometry = geometry), size = 0.1) +
  scale_fill_identity() +
  annotation_custom(
    ggplotGrob(
      tric_educ_disc$key +
        labs(L = '0-2', T = '3-4', R = '5-8')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  ) +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in educational attainment',
       subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.')
```

![](README_files/figure-gfm/unnamed-chunk-11-1.png)<!-- -->

## Ternary centering

While 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.

``` r
tric_lf_non_centered <- Tricolore(euro_example, breaks = Inf,
                                  'lf_pri', 'lf_sec', 'lf_ter')

euro_example$rgb_lf_non_centered <- tric_lf_non_centered$rgb

ggplot(euro_example) +
  geom_sf(aes(fill = rgb_lf_non_centered, geometry = geometry), size = 0.1) +
  scale_fill_identity() +
  annotation_custom(
    ggplotGrob(tric_lf_non_centered$key +
                 labs(L = '% Primary', T = '% Secondary', R = '% Tertiary')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  ) +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in labor force composition',
       subtitle = 'Regional distribution of labor force across the three sectors in 2016.')
```

![](README_files/figure-gfm/unnamed-chunk-12-1.png)<!-- -->

A 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.

Centering 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.

``` r
tric_lf_centered <-
  Tricolore(euro_example,
            'lf_pri', 'lf_sec', 'lf_ter',
            center = NA, crop = FALSE)

euro_example$rgb_lf_centered <- tric_lf_centered$rgb

ggplot(euro_example) +
  geom_sf(aes(fill = rgb_lf_centered, geometry = geometry), size = 0.1) +
  scale_fill_identity() +
  annotation_custom(
    ggplotGrob(
      tric_lf_centered$key +
        labs(L = '% Primary', T = '% Secondary', R = '% Tertiary')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  ) +
  theme_void() +
  coord_sf(datum = NA) +
  labs(title = 'European inequalities in labor force composition',
       subtitle = 'Regional distribution of labor force across the three sectors in 2016.')
```

![](README_files/figure-gfm/unnamed-chunk-13-1.png)<!-- -->

## Contributing

This software is an academic project. We welcome any issues and pull
requests.

Please report any bugs you find by submitting an issue on
github.com/jschoeley/tricolore/issues.

If 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).


================================================
FILE: cran-comments.md
================================================
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.

## Test environments

* Linux Mint 21.3, R 4.5.2
* macOS 15.7.2, R 4.5.2
* Microsoft Windows Server 2025 10.0.26100, R 4.5.2
* Ubuntu 24.04.3, R devel
* Ubuntu 24.04.3, R 4.5.2
* Ubuntu 24.04.3, R 4.4.3 

## R CMD check results

> 0 errors ✔ | 0 warnings ✔ | 0 notes ✔

## Test results

> [ FAIL 0 | WARN 0 | SKIP 0 | PASS 39 ]

## CRAN maintainer comments

- FIXED invalid URLs

> Found the following (possibly) invalid URLs:
> https://ec.europa.eu/eurostat/web/gisco/geodata/reference-data/administrative-units-statistical-units/
> 
> Please fix and resubmit.
> 
> Best,
> Uwe Ligges


================================================
FILE: data-raw/euro_basemap.R
================================================
#'---
#' title: A flat and simplified map of Europe
#' author: Jonas Schöley
#' date: 2018-08-28
#'---

library(tidyverse)
library(sf)
library(rnaturalearth)

eura_sf <-
  # download geospatial data for European, Asian and African countries
  ne_countries(continent = c('europe', 'asia', 'africa'), returnclass = 'sf',
               scale = 50) %>%
  # project to crs 3035
  st_transform(crs = 3035) %>%
  # merge into single polygon
  st_union(by_feature = FALSE) %>%
  st_crop(xmin = 25e5, xmax = 75e5, ymin = 13.5e5, ymax = 54.5e5)

# draw a basemap of Europe
euro_basemap <-
  ggplot(eura_sf) +
  geom_sf(color = NA, fill = 'grey90') +
  coord_sf(expand = FALSE, datum = NA) +
  theme_void() +
  theme(panel.border = element_rect(fill = NA, color = 'grey90', linewidth = 1))

save(euro_basemap, file = './data-raw/euro_basemap.RData', compress = 'xz')


================================================
FILE: data-raw/euro_example.R
================================================
#'---
#' title: Geodata for European NUTS-2 regions with added variables
#' author: Jonas Schöley
#' date: 2019-07-19
#'---

# Init --------------------------------------------------------------------

library(tidyverse)
library(stringi)
library(sf)
library(rmapshaper)
library(eurostat)

# European NUTS-2 geodata -------------------------------------------------

# download geodata on nuts-2 regions
euro_geo_nuts2 <-
  get_eurostat_geospatial(output_class = 'sf',
                          resolution = '60', nuts_level = 2, year = 2016) %>%
  # exclude some regions which don't report
  # the statistics we're interested in
  filter(!(str_detect(geo, '^AL') | str_detect(geo, '^LI') | geo == 'FI20')) %>%
  # project to crs 3035
  st_transform(crs = 3035) %>%
  # pseudo-buffer regions to avoid self-intersection errors
  st_buffer(0) %>%
  # crop to Europe
  st_crop(xmin = 25e5, xmax = 75e5, ymin = 13.5e5, ymax = 54.5e5) %>%
  # simplify to save space
  ms_simplify(keep = 0.05, keep_shapes = TRUE) %>%
  # transliterate non-ASCII characters in region names
  # (so that CRAN-check stops complaining)
  mutate(
    name = stri_trans_general(NUTS_NAME, id = 'any-latin; latin-ascii')
  ) %>%
  # select nuts id, region name and geometry columns
  select(id, name, geometry)

# Download data on European educational composition -----------------------

# download data on education composition by NUTS-2 level for Europe
educ <- get_eurostat('edat_lfse_04')

# select data for 2016 and calculate shares
euro_education <-
  educ %>%
  mutate(year = lubridate::year(time),
         id = as.character(geo)) %>%
  # year 2016, total population, nuts 2 levels
  filter(year == 2016,
         str_length(geo) == 4,
         isced11 %in% c('ED0-2', 'ED3_4', 'ED5-8'),
         sex == 'T') %>%
  mutate(values = values/100) %>%
  spread(isced11, values) %>%
  select(id, ed_0to2 = `ED0-2`, ed_3to4 = `ED3_4`, ed_5to8 = `ED5-8`) %>%
  drop_na()

# Download data on European labor-force composition -----------------------

# download data on labor-force composition by NUTS-2 level for Europe
lf <- get_eurostat("lfst_r_lfe2en2")

# select data for 2016, recode to ternary sectors and calculate shares
euro_sectors <-
  lf %>%
  # recode time as year and geo as character
  mutate(
    year = as.integer(lubridate::year(time)),
    geo = as.character(geo)
  ) %>%
  # subset to total age, year 2016 and NUTS-2 regions
  filter(
    age == 'Y_GE15',
    str_length(geo) == 4,
    year == 2016
  ) %>%
  # if a sector wasn't reported, assume no one worked there
  # (this is motivated by the "missing" agricultural workers in innner london)
  complete(nace_r2, geo, year, fill = list(values = 0)) %>%
  # recode into three sectors
  mutate(
    sector = recode(as.character(nace_r2),
                    `A` = 'primary',
                    `B-E` = 'secondary',
                    `F` = 'secondary'),
    sector = ifelse(!sector %in% c('primary', 'secondary', 'TOTAL'),
                    'tertiary',
                    sector)
  ) %>%
  group_by(year, geo, sector) %>%
  summarise(N = sum(values, na.rm = TRUE)) %>%
  ungroup() %>%
  # calculate shares on total
  spread(sector, N) %>%
  mutate_at(vars(primary, secondary, tertiary), .funs = ~ ./TOTAL) %>%
  # simplify
  select(id = geo, lf_pri = primary, lf_sec = secondary, lf_ter = tertiary) %>%
  drop_na()

# Join compositional data with geodata ------------------------------------

euro_example <-
  euro_geo_nuts2 %>%
  left_join(euro_education, 'id') %>%
  left_join(euro_sectors, 'id') %>%
  arrange(id)

save(
  euro_example,
  file = './data-raw/euro_example.RData',
  compress = 'xz',
  version = 2
)

# Test --------------------------------------------------------------------

# library(leaflet)
# foo <- tricolore::Tricolore(euro_example,
#                             p1 = 'lf_pri', p2 = 'lf_sec', p3 = 'lf_ter',
#                             center = NA, hue = 0.2)
# euro_example %>%
#   st_transform(crs = 4326) %>%
#   leaflet() %>%
#   addProviderTiles(providers$Esri.WorldTerrain) %>%
#   addPolygons(color = str_sub(foo$rgb, 1, 7),
#               weight = 1, smoothFactor = 0.1,
#               fillColor = str_sub(foo$rgb, 1, 7),
#               fillOpacity = 1,
#               popup =
#                 paste0(
#                   euro_example$id, euro_example$name, '</br>',
#                   'Primary: ',
#                   formatC(euro_example$lf_pri*100,
#                           digits = 1, format = 'f'), '%</br>',
#                   ' Secondary: ',
#                   formatC(euro_example$lf_sec*100,
#                           digits = 1, format = 'f'), '%</br>',
#                   ' Tertiary: ',
#                   formatC(euro_example$lf_ter*100,
#                           digits = 1, format = 'f'), '%</br>'
#                 )
#   )
# foo <- tricolore::Tricolore(euro_example,
#                             p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8', hue = 0.2)
# euro_example %>%
#   st_transform(crs = 4326) %>%
#   leaflet() %>%
#   addProviderTiles(providers$Esri.WorldTerrain) %>%
#   addPolygons(color = str_sub(foo$rgb, 1, 7),
#               weight = 1, smoothFactor = 0.1,
#               fillColor = str_sub(foo$rgb, 1, 7),
#               fillOpacity = 1,
#               popup =
#                 paste0(
#                   euro_example$id, euro_example$name, '</br>',
#                   'Primary: ',
#                   formatC(euro_example$ed_0to2*100,
#                           digits = 1, format = 'f'), '%</br>',
#                   ' Secondary: ',
#                   formatC(euro_example$ed_3to4*100,
#                           digits = 1, format = 'f'), '%</br>',
#                   ' Tertiary: ',
#                   formatC(euro_example$ed_5to8*100,
#                           digits = 1, format = 'f'), '%</br>'
#                 )
#   )


================================================
FILE: inst/CITATION
================================================
citHeader('To cite tricolore in publications, please use:')

bibentry(
  bibtype = 'Article',
  author = c(person('Jonas', 'Schöley', role = c('aut', 'cre')), person('Ilya', 'Kashnitsky', role = 'aut')),
  title = 'tricolore. A flexible color scale for ternary compositions',
  journal = 'CRAN',
  year = '2025',
  note = 'Version 1.2.6',
  url = 'https://cran.r-project.org/package=tricolore',
  textVersion = 'J. Schöley and I. Kashnitsky (2024). tricolore: A flexible
  color scale for ternary compositions. Version 1.2.4.  CRAN. URL https://cran.r-project.org/package=tricolore'
)

bibentry(
  bibtype = 'Article',
  author = person('Jonas', 'Schöley'),
  title = 'The centered ternary balance scheme. A technique to visualize surfaces of unbalanced three-part compositions',
  journal      = 'Demographic Research',
  year         = '2021',
  month        = 'mar',
  pages        = '443--458',
  volume       = '44',
  doi          = '10.4054/DemRes.2021.44.19',
  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'
)


================================================
FILE: inst/shiny/app.R
================================================
library(shiny)
library(sf)
library(ggtern)
library(tricolore)

# UI ----------------------------------------------------------------------

ui <- fluidPage(

  titlePanel(title = 'Tricolore: A flexible color scale for ternary compositions'),

  sidebarLayout(

    # INPUT
    sidebarPanel(width = 3,
                 radioButtons(inputId = 'data', label = 'Data', inline = TRUE,
                              choices = list('Labour force' = 'lf',
                                             'Education' = 'educ'),
                              selected = 'educ'),
                 radioButtons(inputId = 'type', label = 'Type', inline = TRUE,
                              choices = list('Default' = 'tricolore',
                                             'Sextant' = 'sextant'),
                              selected = 'tricolore'),
                 conditionalPanel(
                   condition = 'input.type == "tricolore"',
                   sliderInput(inputId = 'hue', label = 'Hue', ticks = FALSE,
                               min = 0, max = 1, step = 0.1, value = 0.2),
                   sliderInput(inputId = 'chroma', label = 'Chroma', ticks = FALSE,
                               min = 0, max = 1, step = 0.1, value = 0.7),
                   sliderInput(inputId = 'lightness', label = 'Lightness', ticks = FALSE,
                               min = 0, max = 1, step = 0.1, value = 0.8),
                   sliderInput(inputId = 'contrast', label = 'Contrast', ticks = FALSE,
                               min = 0, max = 1, step = 0.1, value = 0.4),
                   sliderInput(inputId = 'spread', label = 'Spread',
                               min = 0.5, max = 2, step = 0.1, value = 1, ticks = FALSE),
                 checkboxInput(inputId = 'discrete', label = 'Discrete', value = FALSE),
                 conditionalPanel(
                   condition = 'input.discrete',
                   sliderInput(inputId = 'breaks', label = 'Breaks', ticks = FALSE,
                               min = 2, max = 20, step = 1, value = 4)
                 )),
                 checkboxInput(inputId = 'center', label = 'Mean centering',
                               value = FALSE),
                 checkboxInput(inputId = 'show_center', label = 'Show center',
                               value = FALSE),
                 checkboxInput(inputId = 'show_data', label = 'Show data',
                               value = TRUE),
                 checkboxInput(inputId = 'crop', label = 'Crop legend',
                               value = FALSE),
                 radioButtons(inputId = 'label_as', label = 'Label as',
                              choices = list('percent-share' = 'pct',
                                             'pct-pt. difference' = 'pct_diff'),
                              selected = 'pct'),
                 verbatimTextOutput(outputId = 'call')
    ),

    # OUTPUT
    mainPanel(plotOutput(outputId = 'example'))
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output) {

  output$call <- renderText({
    paste0(
      if (input$type == 'tricolore') 'Tricolore(',
      if (input$type == 'sextant') 'TricoloreSextant(',
      "euro_example, ",
      if (input$data == 'educ') "p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8'",
      if (input$data == 'lf') "p1 = 'lf_pri', p2 = 'lf_sec', p3 = 'lf_ter'",
      ', center = ', ifelse(input$center, 'NA', 'rep(1/3,3)'),
      if (input$type == 'tricolore') {
        paste0(
          ', breaks = ', ifelse(input$discrete, input$breaks, 'Inf'),
          ', hue = ', input$hue,
          ', chroma = ', input$chroma,
          ', lightness = ', input$lightness,
          ', contrast = ', input$contrast,
          ', spread = ', input$spread
        )
      },
      ', legend = TRUE',
      ', show_data = ', input$show_data,
      ', show_center = ', input$show_center,
      ', label_as = "', input$label_as, '"',
      ', crop = ', input$crop, ')'
    )
  })

  output$example <- renderPlot(res = 120, width = 1000, height = 800, {

    if (input$data == 'educ') {
      p1 = 'ed_0to2'; p2 = 'ed_3to4'; p3 = 'ed_5to8'
      title = 'Composition of education levels in European regions 2016\n'
    }
    if (input$data == 'lf') {
      p1 = 'lf_pri'; p2 = 'lf_sec'; p3 = 'lf_ter'
      title = 'Labor force composition in European regions 2016\n'
    }

    if (input$type == 'tricolore') {

      # mix color, generate legend
      mixed <- Tricolore(euro_example,
                         p1 = p1, p2 = p2, p3 = p3,
                         center = if (input$center) NA else rep(1/3,3),
                         breaks = ifelse(input$discrete, input$breaks, Inf),
                         hue = input$hue, chroma = input$chroma,
                         lightness = input$lightness,
                         contrast = input$contrast,
                         spread = input$spread,
                         show_data = input$show_data,
                         show_center = input$show_center,
                         label_as = input$label_as,
                         crop = input$crop,
                         legend = TRUE)

    }

    if (input$type == 'sextant') {

      # mix color, generate legend
      mixed <- TricoloreSextant(euro_example,
                                p1 = p1, p2 = p2, p3 = p3,
                                center = if (input$center) NA else rep(1/3,3),
                                show_data = input$show_data,
                                show_center = input$show_center,
                                label_as = input$label_as,
                                crop = input$crop,
                                legend = TRUE)

    }

    # customize legend
    lgnd <- mixed[['key']] +
      labs(x = 'Primary', y = 'Secondary', z = 'Tertiary',
           subtitle =
             paste0(
               title,
               ifelse(input$center,
                      'Colors show deviation from average composition\n',
                      'Colors show deviations from balanced composition\n'),
               'Data by eurostat'
             )
      ) +
      theme(
        plot.background = element_blank(),
        plot.subtitle = element_text(size = 8),
        panel.background = element_blank(),
        tern.plot.background = element_blank(),
        tern.panel.background = element_blank(),
      )

    # merge data and map
    euro_example$rgb <- mixed[['rgb']]

    # generate map
    euro_map <-
      euro_basemap +
      geom_sf(aes(fill = rgb, geometry = geometry), color = NA,
              data = euro_example) +
      annotation_custom(ggplotGrob(lgnd),
                        xmin = 54e5, xmax = 74e5,
                        ymin = 8e5, ymax = 80e5) +
      scale_fill_identity() +
      coord_sf(expand = FALSE, datum = NA, default = TRUE)

    print(euro_map)
  })

}

shinyApp(ui, server)


================================================
FILE: man/BasicKey.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{BasicKey}
\alias{BasicKey}
\title{Template for Ternary Key}
\usage{
BasicKey(legend_surface, limits, brklab, show_center, center, lwd)
}
\arguments{
\item{legend_surface}{A data frame with numeric 'id', 'p1', 'p2', 'p3' and
character column 'rgb'.}

\item{limits}{A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.}

\item{brklab}{Breaks and labels as returned by \code{\link{BreaksAndLabels}}.}

\item{show_center}{Should the center be marked on the legend? (logical)}

\item{center}{Ternary coordinates of the grey-point.}

\item{lwd}{A numeric scalar giving the linewidth of the legend surface
polygons.}
}
\value{
A ggtern grob.
}
\description{
Return various types of breaks and labels for ternary color keys.
}
\keyword{internal}


================================================
FILE: man/BreaksAndLabels.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{BreaksAndLabels}
\alias{BreaksAndLabels}
\title{Breaks and Labels for Ternary Color Key}
\usage{
BreaksAndLabels(type, center = NULL, breaks = NULL)
}
\arguments{
\item{type}{An integer 1, 2, or 3.}

\item{center}{Ternary coordinates of the grey-point.}

\item{breaks}{Number of breaks in the discrete color scale. An integer >1.
Values above 99 imply no discretization.}
}
\value{
A list of lists containing breaks and labels for each of the 3
  ternary axes.
}
\description{
Return various types of breaks and labels for ternary color keys.
}
\examples{
# NOTE: only intended for internal use and not part of the API
tricolore:::BreaksAndLabels(1, breaks = 3)
tricolore:::BreaksAndLabels(2)
tricolore:::BreaksAndLabels(3, center = c(1/3, 1/3, 1/3))

}
\keyword{internal}


================================================
FILE: man/Centre.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{Centre}
\alias{Centre}
\title{Compositional Centre}
\usage{
Centre(P)
}
\arguments{
\item{P}{n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.}
}
\value{
The centre of P as an m element numeric vector.
}
\description{
Calculate the centre of a compositional data set.
}
\examples{
# NOTE: only intended for internal use and not part of the API
P <- prop.table(matrix(runif(300), 100), margin = 1)
tricolore:::Centre(P)

}
\references{
Von Eynatten, H., Pawlowsky-Glahn, V., & Egozcue, J. J. (2002).
Understanding perturbation on the simplex: A simple method to better
visualize and interpret compositional data in ternary diagrams.
Mathematical Geology, 34(3), 249-257.

Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture
Notes on Compositional Data Analysis. Retrieved from
https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf
}
\keyword{internal}


================================================
FILE: man/ColorKeySextant.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{ColorKeySextant}
\alias{ColorKeySextant}
\title{Sextant Scheme Legend}
\usage{
ColorKeySextant(
  center,
  values,
  label_as,
  show_center,
  limits = matrix(0:1, nrow = 2, ncol = 3)
)
}
\arguments{
\item{center}{Ternary coordinates of the sextant meeting point.}

\item{values}{6 element character vector of rgb-codes.}

\item{label_as}{"pct" for percent-share labels or "pct_diff" for
percent-point-difference from center labels.}

\item{show_center}{Should the center be marked on the legend? (logical)}

\item{limits}{A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.}
}
\value{
A ggtern grob.
}
\description{
Plot a sextant scheme legend.
}
\examples{
# NOTE: only intended for internal use and not part of the API
tricolore:::ColorKeySextant(center = prop.table(runif(3)),
                            values = c('#01A0C6', '#B8B3D8', '#F11D8C',
                                       '#FFB3B3', '#FFFF00', '#B3DCC3'),
                            label_as = 'pct_diff', show_center = TRUE)

}
\keyword{internal}


================================================
FILE: man/ColorKeyTricolore.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{ColorKeyTricolore}
\alias{ColorKeyTricolore}
\title{Ternary Balance Scheme Legend}
\usage{
ColorKeyTricolore(
  center,
  breaks,
  h_,
  c_,
  l_,
  contrast,
  spread,
  label_as,
  show_center,
  limits = matrix(0:1, nrow = 2, ncol = 3)
)
}
\arguments{
\item{center}{Ternary coordinates of the grey-point.}

\item{breaks}{Number of breaks in the discrete color scale. An integer >1.
Values above 99 imply no discretization.}

\item{h_}{Primary hue of the first ternary element in angular degrees [0, 360].}

\item{c_}{Maximum possible chroma of mixed colors [0, 200].}

\item{l_}{Lightness of mixed colors [0, 100].}

\item{contrast}{Lightness contrast of the color scale [0, 1).}

\item{spread}{Spread of the color scale around center > 0.}

\item{label_as}{"pct" for percent-share labels or "pct_diff" for
percent-point-difference from center labels.}

\item{show_center}{Should the center be marked on the legend? (logical)}

\item{limits}{A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.}
}
\value{
A ggtern grob.
}
\description{
Plot a ternary balance scheme legend.
}
\examples{
# NOTE: only intended for internal use and not part of the API
tricolore:::ColorKeyTricolore(center = rep(1/3, 3), breaks = 4,
                              h_ = 80, c_ = 140, l_ = 80,
                              contrast = 0.4, spread = 1,
                              label_as = "pct", show_center = FALSE)

}
\keyword{internal}


================================================
FILE: man/ColorMapSextant.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{ColorMapSextant}
\alias{ColorMapSextant}
\title{Sextant Encoding of Ternary Composition}
\usage{
ColorMapSextant(P, center, values)
}
\arguments{
\item{P}{n by 3 matrix of ternary compositions [p1, p2, p3](i) for
i=1, ..., n.}

\item{center}{Ternary coordinates of the sextant meeting point.}

\item{values}{6 element character vector of rgb-codes.}
}
\value{
An n row data frame giving, for each row of the input P, the input
proportions [p1, p2, p3], sextant id (sextant) and the hex-rgb string of the
mixed colors (rgb).
}
\description{
Return the sextant scheme colors for a matrix of ternary compositions.
}
\examples{
# NOTE: only intended for internal use and not part of the API
P <- prop.table(matrix(runif(9), ncol = 3), 1)
tricolore:::ColorMapSextant(P, c(1/3, 1/3, 1/3),
                            c('#01A0C6', '#B8B3D8', '#F11D8C', '#FFB3B3',
                              '#FFFF00', '#B3DCC3'))
}
\keyword{internal}


================================================
FILE: man/ColorMapTricolore.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{ColorMapTricolore}
\alias{ColorMapTricolore}
\title{CIE-Lch Mixture of Ternary Composition}
\usage{
ColorMapTricolore(P, center, breaks, h_, c_, l_, contrast, spread)
}
\arguments{
\item{P}{n by 3 matrix of ternary compositions [p1, p2, p3](i) for
i=1, ..., n.}

\item{center}{Ternary coordinates of the grey-point.}

\item{breaks}{Number of breaks in the discrete color scale. An integer >1.
Values above 99 imply no discretization.}

\item{h_}{Primary hue of the first ternary element in angular degrees [0, 360].}

\item{c_}{Maximum possible chroma of mixed colors [0, 200].}

\item{l_}{Lightness of mixed colors [0, 100].}

\item{contrast}{Lightness contrast of the color scale [0, 1).}

\item{spread}{Spread of the color scale around center > 0.}
}
\value{
An n row data frame giving, for each row of the input P, the input
proportions [p1, p2, p3], parameters of the color mixture (h, c, l) and the
hex-rgb string of the mixed colors (rgb).
}
\description{
Return the ternary balance scheme colors for a matrix of ternary compositions.
}
\examples{
# NOTE: only intended for internal use and not part of the API
P <- prop.table(matrix(runif(9), ncol = 3), 1)
tricolore:::ColorMapTricolore(P, center = rep(1/3, 3), breaks = 4,
                              h_ = 80, c_ = 140, l_ = 80,
                              contrast = 0.4, spread = 1)

}
\keyword{internal}


================================================
FILE: man/DemoTricolore.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{DemoTricolore}
\alias{DemoTricolore}
\title{Interactive Tricolore Demonstration}
\usage{
DemoTricolore()
}
\value{
Opens a shiny app session.
}
\description{
An interactive demonstration of the tricolore color scale inspired by the
colorbrewer2.org application. Helps in picking the right color scale for your
data.
}


================================================
FILE: man/GeometricMean.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{GeometricMean}
\alias{GeometricMean}
\title{Geometric Mean}
\usage{
GeometricMean(x, na.rm = TRUE, zero.rm = TRUE)
}
\arguments{
\item{x}{Numeric vector.}

\item{na.rm}{Should NAs be removed? (default=TRUE)}

\item{zero.rm}{Should zeros be removed? (default=TRUE)}
}
\value{
The geometric mean as numeric scalar.
}
\description{
Calculate the geometric mean for a numeric vector.
}
\examples{
# NOTE: only intended for internal use and not part of the API
tricolore:::GeometricMean(0:100)
tricolore:::GeometricMean(0:100, zero.rm = FALSE)

}
\keyword{internal}


================================================
FILE: man/Pertube.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{Pertube}
\alias{Pertube}
\title{Compositional Pertubation}
\usage{
Pertube(P, c = rep(1/3, 3))
}
\arguments{
\item{P}{n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.}

\item{c}{Compositional pertubation vector [c1, ..., cm].}
}
\value{
n by m matrix of pertubated compositions.
}
\description{
Pertubate a compositional data set by a compositional vector.
}
\examples{
# NOTE: only intended for internal use and not part of the API
P <- prop.table(matrix(runif(12), 4), margin = 1)
cP <- tricolore:::Pertube(P, 1/tricolore:::Centre(P))
tricolore:::Centre(cP)

}
\references{
Von Eynatten, H., Pawlowsky-Glahn, V., & Egozcue, J. J. (2002).
Understanding perturbation on the simplex: A simple method to better
visualize and interpret compositional data in ternary diagrams.
Mathematical Geology, 34(3), 249-257.

Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture
Notes on Compositional Data Analysis. Retrieved from
https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf
}
\keyword{internal}


================================================
FILE: man/PowerScale.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{PowerScale}
\alias{PowerScale}
\title{Compositional Powering}
\usage{
PowerScale(P, scale = 1)
}
\arguments{
\item{P}{n by m matrix of compositions [p1, ..., pm]_i for i=1,...,n.}

\item{scale}{Power scalar.}
}
\value{
n by m numeric matrix of powered compositions.
}
\description{
Raise a compositional data-set to a given power.
}
\examples{
# NOTE: only intended for internal use and not part of the API
P <- prop.table(matrix(runif(12), 4), margin = 1)
tricolore:::PowerScale(P, 2)

}
\references{
Pawlowsky-Glahn, V., Egozcue, J. J., & Tolosana-Delgado, R. (2007). Lecture
Notes on Compositional Data Analysis. Retrieved from
https://dugi-doc.udg.edu/bitstream/handle/10256/297/CoDa-book.pdf
}
\keyword{internal}


================================================
FILE: man/TernaryCenterGrid.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TernaryCenterGrid}
\alias{TernaryCenterGrid}
\title{Return Ternary Gridlines Centered Around Some Composition}
\usage{
TernaryCenterGrid(center, spacing)
}
\arguments{
\item{center}{The center of the grid.
A vector of ternary coordinates [p1, p2, p3].}

\item{spacing}{The spacing of the grid in percent-point increments.
A numeric > 0.}
}
\value{
A list of lists.
}
\description{
Return Ternary Gridlines Centered Around Some Composition
}
\examples{
# NOTE: only intended for internal use and not part of the API
tricolore:::TernaryCenterGrid(c(1/6, 2/6, 3/6), 10)

}
\keyword{internal}


================================================
FILE: man/TernaryDistance.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TernaryDistance}
\alias{TernaryDistance}
\title{Distance Between Points in Ternary Coordinates}
\usage{
TernaryDistance(p, C)
}
\arguments{
\item{p}{A vector of ternary coordinates [p1, p2, p3].}

\item{C}{n by 3 matrix of ternary coordinates [p1, p2, p3](i) for i=1,...,n.}
}
\value{
A numeric vector of distances between coordinate p and all
  coordinates in C.
}
\description{
The distances between ternary coordinate p and a set of ternary coordinates C.
}
\examples{
# NOTE: only intended for internal use and not part of the API
p <- c(0.5, 0.2, 0.3)
C <- prop.table(matrix(runif(3*10), ncol = 3), 1)
tricolore:::TernaryDistance(p, C)

}
\references{
https://en.wikipedia.org/wiki/Barycentric_coordinate_system#Distance_between_points
}
\keyword{internal}


================================================
FILE: man/TernaryLimits.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TernaryLimits}
\alias{TernaryLimits}
\title{Return the Limits of Ternary Coordinates}
\usage{
TernaryLimits(P, na.rm = TRUE)
}
\arguments{
\item{P}{n by 3 matrix of ternary coordinates [p1, p2, p3](i) for
i=1,...,n.}

\item{na.rm}{Should NAs be removed? (default=TRUE)}
}
\value{
A 2 by 3 matrix of lower and upper limits for p1, p2 and p3.
}
\description{
Return the Limits of Ternary Coordinates
}
\examples{
# NOTE: only intended for internal use and not part of the API
P <- prop.table(matrix(runif(9), ncol = 3), 1)
tricolore:::TernaryLimits(P)

}
\keyword{internal}


================================================
FILE: man/TernaryMeshCentroids.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TernaryMeshCentroids}
\alias{TernaryMeshCentroids}
\title{Centroid Coordinates of Sub-Triangles in Segmented Equilateral Triangle}
\usage{
TernaryMeshCentroids(k)
}
\arguments{
\item{k}{Number of rows in the segmented equilateral triangle.}
}
\value{
A numeric matrix of with index and barycentric centroid coordinates
  of regions id=1,...,k^2.
}
\description{
Segment an equilateral triangle into k^2 equilateral sub-triangles and return
the barycentric centroid coordinates of each sub-triangle.
}
\examples{
# NOTE: only intended for internal use and not part of the API
tricolore:::TernaryMeshCentroids(1)
tricolore:::TernaryMeshCentroids(2)
tricolore:::TernaryMeshCentroids(3)

}
\references{
S. H. Derakhshan and C. V. Deutsch (2009): A Color Scale for Ternary Mixtures.
}
\keyword{internal}


================================================
FILE: man/TernaryMeshVertices.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TernaryMeshVertices}
\alias{TernaryMeshVertices}
\title{Vertex Coordinates of Sub-Triangles in Segmented Equilateral Triangle}
\usage{
TernaryMeshVertices(C)
}
\arguments{
\item{C}{n by 4 matrix of barycentric centroid coordinates of n=k^2
sub-triangles. Column order: id, p1, p2, p3 with id=1,...,k^2.}
}
\value{
A numeric matrix with index, vertex id and barycentric vertex
  coordinates for each of the k^2 sub-triangles.
}
\description{
Given the barycentric centroid coordinates of the sub-triangles in an
equilateral triangle subdivided into k^2 equilateral sub-triangles, return
the barycentric vertex coordinates of each sub-triangle.
}
\examples{
# NOTE: only intended for internal use and not part of the API
k = 2
C <- tricolore:::TernaryMeshCentroids(k)
tricolore:::TernaryMeshVertices(C)

}
\references{
S. H. Derakhshan and C. V. Deutsch (2009): A Color Scale for Ternary Mixtures.
}
\keyword{internal}


================================================
FILE: man/TernaryNearest.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TernaryNearest}
\alias{TernaryNearest}
\title{For Ternary Coordinates P Return the Nearest Coordinate in Set C}
\usage{
TernaryNearest(P, C)
}
\arguments{
\item{P, C}{n by 3 matrix of ternary coordinates [p1, p2, p3](i) for
i=1,...,n. n may be different for P and C.}
}
\value{
n by 3 matrix of ternary coordinates in C.
}
\description{
For Ternary Coordinates P Return the Nearest Coordinate in Set C
}
\examples{
# NOTE: only intended for internal use and not part of the API
P <- prop.table(matrix(runif(9), ncol = 3), 1)
C <- tricolore:::TernaryMeshCentroids(2)[,-1]
tricolore:::TernaryNearest(P, C)

}
\keyword{internal}


================================================
FILE: man/TernarySextantVertices.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TernarySextantVertices}
\alias{TernarySextantVertices}
\title{Vertex Coordinates of Sextants in Equilateral Triangle}
\usage{
TernarySextantVertices(center)
}
\arguments{
\item{center}{The sextant center.
A vector of ternary coordinates [p1, p2, p3].}
}
\value{
Index, vertex id and barycentric vertex coordinates for each of the
        6 sextants.
}
\description{
Given a barycentric center coordinate return the vertex coordinates of the
of the sextant regions.
}
\examples{
# NOTE: only intended for internal use and not part of the API
tricolore:::TernarySextantVertices(rep(1/3, 3))

}
\keyword{internal}


================================================
FILE: man/TernarySurroundingSextant.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TernarySurroundingSextant}
\alias{TernarySurroundingSextant}
\title{Return Surrounding Sextant of Barycentric Coordinates}
\usage{
TernarySurroundingSextant(P, center)
}
\arguments{
\item{P}{n by 3 matrix of ternary coordinates [p1, p2, p3](i) for
i=1,...,n.}

\item{center}{The sextant center.
A vector of ternary coordinates [p1, p2, p3].}
}
\value{
An n element character vector of sextant id's 1 to 6.
}
\description{
Given barycentric coordinates return the id of the surrounding sextant.
}
\examples{
# NOTE: only intended for internal use and not part of the API
P <- prop.table(matrix(runif(9), ncol = 3), 1)
tricolore:::TernarySurroundingSextant(P, rep(1/3, 3))

}
\keyword{internal}


================================================
FILE: man/Tricolore.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{Tricolore}
\alias{Tricolore}
\title{Ternary Balance Color Scale}
\usage{
Tricolore(
  df,
  p1,
  p2,
  p3,
  center = rep(1/3, 3),
  breaks = ifelse(identical(center, rep(1/3, 3)), 4, Inf),
  hue = 0.2,
  chroma = 0.7,
  lightness = 0.8,
  contrast = 0.4,
  spread = 1,
  legend = TRUE,
  show_data = TRUE,
  show_center = ifelse(identical(center, rep(1/3, 3)), FALSE, TRUE),
  label_as = ifelse(identical(center, rep(1/3, 3)), "pct", "pct_diff"),
  crop = FALSE,
  input_validation = TRUE
)
}
\arguments{
\item{df}{Data frame of compositional data.}

\item{p1}{Column name for variable in df giving first proportion
of ternary composition (string).}

\item{p2}{Column name for variable in df giving second proportion
of ternary composition (string).}

\item{p3}{Column name for variable in df giving third proportion
of ternary composition (string).}

\item{center}{Ternary coordinates of the color scale center.
(default = 1/3,1/3,1/3). NA puts center over the compositional
mean of the data.}

\item{breaks}{Number of per-axis breaks in the discrete color scale.
An integer >1. Values above 99 imply no discretization.}

\item{hue}{Primary hue of the first ternary element (0 to 1).}

\item{chroma}{Maximum possible chroma of mixed colors (0 to 1).}

\item{lightness}{Lightness of mixed colors (0 to 1).}

\item{contrast}{Lightness contrast of the color scale (0 to 1).}

\item{spread}{The spread of the color scale. Choose values > 1 to focus the
color scale on the center.}

\item{legend}{Should a legend be returned along with the colors? (default=TRUE)}

\item{show_data}{Should the data be shown on the legend? (default=TRUE)}

\item{show_center}{Should the center be shown on the legend?
(default=FALSE if center is at c(1/3, 1/3, 1/3), otherwise TRUE)}

\item{label_as}{"pct" for percent-share labels or "pct_diff" for
percent-point-difference from center labels.
(default='pct' if center is at c(1/3, 1/3, 1/3), otherwise 'pct_diff')}

\item{crop}{Should the legend be cropped to the data? (default=FALSE)}

\item{input_validation}{Should the function arguments be validated? (default=TRUE)}
}
\value{
\itemize{
\item legend=FALSE: A vector of rgbs hex-codes representing the ternary balance
scheme colors.
\item legend=TRUE: A list with elements "rgb" and "key".
}
}
\description{
Color-code three-part compositions with a ternary balance color scale and
return a color key.
}
\examples{
P <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))
Tricolore(P, 'V1', 'V2', 'V3')

}


================================================
FILE: man/TricoloreSextant.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{TricoloreSextant}
\alias{TricoloreSextant}
\title{Ternary Sextant Color Scale}
\usage{
TricoloreSextant(
  df,
  p1,
  p2,
  p3,
  center = rep(1/3, 3),
  values = c("#FFFF00", "#B3DCC3", "#01A0C6", "#B8B3D8", "#F11D8C", "#FFB3B3"),
  legend = TRUE,
  show_data = TRUE,
  show_center = TRUE,
  label_as = ifelse(identical(center, rep(1/3, 3)), "pct", "pct_diff"),
  crop = FALSE,
  input_validation = TRUE
)
}
\arguments{
\item{df}{Data frame of compositional data.}

\item{p1}{Column name for variable in df giving first proportion
of ternary composition (string).}

\item{p2}{Column name for variable in df giving second proportion
of ternary composition (string).}

\item{p3}{Column name for variable in df giving third proportion
of ternary composition (string).}

\item{center}{Ternary coordinates of the color scale center.
(default = 1/3,1/3,1/3). NA puts center over the compositional
mean of the data.}

\item{values}{6 element character vector of rgb-codes.}

\item{legend}{Should a legend be returned along with the colors? (default=TRUE)}

\item{show_data}{Should the data be shown on the legend? (default=TRUE)}

\item{show_center}{Should the center be shown on the legend?
(default=FALSE if center is at c(1/3, 1/3, 1/3), otherwise TRUE)}

\item{label_as}{"pct" for percent-share labels or "pct_diff" for
percent-point-difference from center labels.
(default='pct' if center is at c(1/3, 1/3, 1/3), otherwise 'pct_diff')}

\item{crop}{Should the legend be cropped to the data? (default=FALSE)}

\item{input_validation}{Should the function arguments be validated? (default=TRUE)}
}
\value{
\itemize{
\item legend=FALSE: A vector of rgbs hex-codes representing the ternary balance
scheme colors.
\item legend=TRUE: A list with elements "rgb" and "key".
}
}
\description{
Color-code three-part compositions with a ternary sextant color scale and
return a color key.
}
\examples{
P <- as.data.frame(prop.table(matrix(runif(3^6), ncol = 3), 1))
TricoloreSextant(P, 'V1', 'V2', 'V3')

}


================================================
FILE: man/ValidateMainArguments.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{ValidateMainArguments}
\alias{ValidateMainArguments}
\title{Validate Main Arguments}
\usage{
ValidateMainArguments(df, p1, p2, p3)
}
\arguments{
\item{df}{Data frame of compositions.}

\item{p1}{Column name for variable in df giving first proportion
of ternary composition (string).}

\item{p2}{Column name for variable in df giving second proportion
of ternary composition (string.}

\item{p3}{Column name for variable in df giving third proportion
of ternary composition (string).}
}
\description{
Validate main arguments of tricolore function.
}
\keyword{internal}


================================================
FILE: man/ValidateParametersShared.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{ValidateParametersShared}
\alias{ValidateParametersShared}
\title{Validate Shared Parameters}
\usage{
ValidateParametersShared(pars)
}
\arguments{
\item{pars}{A named list of parameters.}
}
\description{
Validate parameters shared across tricolore functions.
}
\keyword{internal}


================================================
FILE: man/ValidateParametersTricolore.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{ValidateParametersTricolore}
\alias{ValidateParametersTricolore}
\title{Validate Tricolore Parameters}
\usage{
ValidateParametersTricolore(pars)
}
\arguments{
\item{pars}{A named list of parameters.}
}
\description{
Validate parameters of Tricolore function.
}
\keyword{internal}


================================================
FILE: man/ValidateParametersTricoloreSextant.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\name{ValidateParametersTricoloreSextant}
\alias{ValidateParametersTricoloreSextant}
\title{Validate TricoloreSextant Parameters}
\usage{
ValidateParametersTricoloreSextant(pars)
}
\arguments{
\item{pars}{A named list of parameters.}
}
\description{
Validate parameters of TricoloreSextant function.
}
\keyword{internal}


================================================
FILE: man/euro_basemap.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\docType{data}
\name{euro_basemap}
\alias{euro_basemap}
\title{Flat Map of European Continent}
\format{
An object of class \code{ggplot} (inherits from \code{ggplot2::ggplot}, \code{ggplot2::gg}, \code{S7_object}, \code{gg}) of length 1.
}
\source{
Derived from geodata provided by the Natural Earth project.
  \url{https://www.naturalearthdata.com/}
}
\usage{
euro_basemap
}
\description{
A ggplot object rendering a flat background map of the European continent.
}
\keyword{datasets}


================================================
FILE: man/euro_example.Rd
================================================
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/tricolore.R
\docType{data}
\name{euro_example}
\alias{euro_example}
\title{NUTS-2 Level Geodata and Compositional Data for Europe}
\format{
A data frame with 312 rows and 9 variables:
  \describe{
    \item{id}{NUTS-2 code.}
    \item{name}{Name of NUTS-2 region.}
    \item{ed_0to2}{Share of population with highest attained education "lower secondary or less".}
    \item{ed_3to4}{Share of population with highest attained education "upper secondary".}
    \item{ed_5to8}{Share of population with highest attained education "tertiary".}
    \item{lf_pri}{Share of labor-force in primary sector.}
    \item{lf_sec}{Share of labor-force in secondary sector.}
    \item{lf_ter}{Share of labor-force in tertiary sector.}
    \item{geometry}{Polygon outlines for regions in sf package format.}
  }
}
\source{
Derived from Eurostats European Geodata.
  (c) EuroGeographics for the administrative boundaries.
  \url{https://gisco-services.ec.europa.eu/distribution/v2/nuts/nuts-2016-files.html}

  Education data derived from Eurostats table "edat_lfse_04".

  Labor-force data derived from Eurostats table "lfst_r_lfe2en2".
}
\usage{
euro_example
}
\description{
A simple-features dataframe containing the NUTS-2 level polygons of European
regions along with regional compositional data on education and labor-force.
}
\details{
Variables starting with "ed" refer to the relative share of population ages
  25 to 64 by educational attainment in the European NUTS-2 regions 2016.

  Variables starting with "lf" refer to the relative share of workers by
  labor-force sector in the European NUTS-2 regions 2016. The original NACE
  (rev. 2) codes have been recoded into the three sectors "primary" (A),
  "secondary" (B-E & F) and "tertiary" (all other NACE codes).
}
\keyword{datasets}


================================================
FILE: tests/testthat/test-global.R
================================================
context('test-global.R')

test_that('GeometricMean() works', {
  expect_equal(GeometricMean(0:4), exp(mean(log(1:4))))
  expect_equal(GeometricMean(0:4, zero.rm = FALSE), 0)
  expect_equal(GeometricMean(c(NA, 0:4), na.rm = TRUE, zero.rm = FALSE), 0)
  expect_equal(GeometricMean(c(NA, 0:4), na.rm = FALSE, zero.rm = FALSE), as.numeric(NA))
  expect_equal(GeometricMean(0:4, na.rm = FALSE, zero.rm = TRUE), exp(mean(log(1:4))))
  expect_equal(GeometricMean(c(NA, 0:4), na.rm = FALSE, zero.rm = TRUE), as.numeric(NA))
  expect_equal(GeometricMean(0, zero.rm = TRUE), NaN)
})

test_that('Centre() works', {
  P <- prop.table(matrix(runif(300), 100), margin = 1)
  expect_equal(prop.table(apply(t(t(P)/Centre(P)), 2, GeometricMean)), rep(1/3, 3))
  expect_equal(NROW(Centre(P)), 3)
  expect_equal(NCOL(Centre(P)), 1)
})


test_that('Pertube() works', {
  P <- prop.table(matrix(runif(300), 100), margin = 1)
  expect_equal(Pertube(P, rep(1/3, 3)), P)
  expect_equal(Centre(Pertube(P, 1/Centre(P))), rep(1/3, 3))
  expect_equal(NROW(Pertube(P, rep(1/3, 3))), 100)
  expect_equal(NCOL(Pertube(P, rep(1/3, 3))), 3)
})

test_that('TernaryMeshCentroids() works', {
  k = sample(2:100, size = 1)
  expect_equal(NROW(TernaryMeshCentroids(k)), k^2)
  expect_equal(TernaryMeshCentroids(k)[,'id'], 1:k^2)
  expect_equal(rowSums(TernaryMeshCentroids(k)[,2:4]), rep(1, k^2))
  expect_equivalent(prop.table(apply(TernaryMeshCentroids(k)[,2:4], 2, GeometricMean)), rep(1/3, 3))
})

test_that('Argument checks work', {
  P <- as.data.frame(prop.table(matrix(runif(300), 100), margin = 1))
  # missing main arguments
  expect_error(Tricolore(p1 = 'V1', p2 = 'V2', p3 = 'V3'),
               'main argument missing')
  expect_error(Tricolore(P, p2 = 'V2', p3 = 'V3'),
               'main argument missing')
  expect_error(Tricolore(P, p1 = 'V1', p3 = 'V3'),
               'main argument missing')
  expect_error(Tricolore(P, p1 = 'V1', p2 = 'V2'),
               'main argument missing')
  expect_error(Tricolore(P, p1 = 'Foo1', p2 = 'V2', p3 = 'V3'),
               'Foo1 not found')
  expect_error(Tricolore(P, p1 = 'V1', p2 = 'Foo2', p3 = 'V3'),
               'Foo2 not found')
  expect_error(Tricolore(P, p1 = 'V1', p2 = 'V2', p3 = 'Foo3'),
               'Foo3 not found')
  # type checks for main arguments
  expect_error(Tricolore(as.matrix(P), p1 = 'V1', p2 = 'V2', p3 = 'V3'),
               'df is not a data frame')
  expect_error(Tricolore(P, p1 = 1, p2 = 2, p3 = 3),
               'not a string')
  expect_error(Tricolore(data.frame(V1 = as.character(P$V1), V2 = P$V2, V3 = P$V3),
                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),
               'variable V1 is not numeric')
  expect_error(Tricolore(data.frame(V1 = P$V1, V2 = as.character(P$V2), V3 = P$V3),
                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),
               'variable V2 is not numeric')
  expect_error(Tricolore(data.frame(V1 = P$V1, V2 = P$V2, V3 = as.character(P$V3)),
                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),
               'variable V3 is not numeric')
  expect_error(Tricolore(data.frame(V1 = -P$V1, V2 = P$V2, V3 = P$V3),
                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),
               'variable V1 contains negative values')
  expect_error(Tricolore(data.frame(V1 = P$V1, V2 = -P$V2, V3 = P$V3),
                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),
               'variable V2 contains negative values')
  expect_error(Tricolore(data.frame(V1 = P$V1, V2 = P$V2, V3 = -P$V3),
                         p1 = 'V1', p2 = 'V2', p3 = 'V3'),
               'variable V3 contains negative values')
})

# NA, Inf, NaN are allowed and are expected to return NA as color
test_that('NA, Inf, NaNs in input return NA in output', {
  P <- data.frame(a = c(1, NA), b = c(0, 0.5), c = c(0, 0.2))
  tric <- Tricolore(P, 'a', 'b', 'c', breaks = Inf)
  expect_equal(tric$rgb, c('#F0C500', NA))
  expect_true(all(c('gg', 'ggplot') %in% class(tric$key)))
  P <- data.frame(a = c(1, Inf), b = c(0, 0.5), c = c(0, 0.2))
  tric <- Tricolore(P, 'a', 'b', 'c', breaks = Inf)
  expect_equal(tric$rgb, c('#F0C500', NA))
  expect_true(all(c('gg', 'ggplot') %in% class(tric$key)))
  P <- data.frame(a = c(1, NaN), b = c(0, 0.5), c = c(0, 0.2))
  tric <- Tricolore(P, 'a', 'b', 'c', breaks = Inf)
  expect_equal(tric$rgb, c('#F0C500', NA))
  expect_true(all(c('gg', 'ggplot') %in% class(tric$key)))
})


================================================
FILE: tests/testthat.R
================================================
library(testthat)
library(tricolore)

test_check('tricolore')


================================================
FILE: vignettes/choropleth_maps_with_tricolore.R
================================================
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  tidy = FALSE,
  comment = "#>",
  fig.width = 6, fig.height = 6
)

## -----------------------------------------------------------------------------
library(tricolore)

## -----------------------------------------------------------------------------
# color-code the data set and generate a color-key
tric <- Tricolore(euro_example, p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8')

## -----------------------------------------------------------------------------
# add the vector of colors to the `euro_example` data
euro_example$rgb <- tric$rgb

## -----------------------------------------------------------------------------
library(ggplot2)

plot_educ <-
  # using sf dataframe `euro_example`...
  ggplot(euro_example) +
  # ...draw a polygon for each region...
  geom_sf(aes(fill = rgb, geometry = geometry), size = 0.1) +
  # ...and color each region according to the color code in the variable `rgb`
  scale_fill_identity()

plot_educ 

## -----------------------------------------------------------------------------
library(ggtern)
plot_educ +
  annotation_custom(
    ggplotGrob(tric$key),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  )

## -----------------------------------------------------------------------------
plot_educ <-
  plot_educ +
  annotation_custom(
    ggplotGrob(tric$key +
                 theme(plot.background = element_rect(fill = NA, color = NA)) +
                 labs(L = '0-2', T = '3-4', R = '5-8')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  )
plot_educ

## -----------------------------------------------------------------------------
plot_educ +
  theme_void() +
  coord_sf(datum = NA) +
  labs(
   title = 'European inequalities in educational attainment',
      subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.'
  )

## -----------------------------------------------------------------------------
# color-code the data set and generate a color-key
tric <- Tricolore(euro_example, p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',
                  breaks = Inf)

# add the vector of colors to the `euro_example` data
euro_example$rgb <- tric$rgb

## -----------------------------------------------------------------------------
library(sf)
library(leaflet)

euro_example %>%
  st_transform(crs = 4326) %>%
  leaflet() %>%
  addPolygons(smoothFactor = 0.1, weight = 0,
              fillColor = euro_example$rgb,
              fillOpacity = 1)

## -----------------------------------------------------------------------------
euro_example %>%
  st_transform(crs = 4326) %>%
  leaflet() %>%
  addProviderTiles(providers$Esri.WorldTerrain) %>%
  addPolygons(smoothFactor = 0.1, weight = 0,
              fillColor = euro_example$rgb,
              fillOpacity = 1,
              popup =
                paste0(
                  '<b>', euro_example$name, '</b></br>',
                  'Primary: ',
                  formatC(euro_example$ed_0to2*100,
                          digits = 1, format = 'f'), '%</br>',
                  'Secondary: ',
                  formatC(euro_example$ed_3to4*100,
                          digits = 1, format = 'f'), '%</br>',
                  'Tertiary: ',
                  formatC(euro_example$ed_5to8*100,
                          digits = 1, format = 'f'), '%</br>'
                )
  )

## -----------------------------------------------------------------------------
makePlotURI <- function(expr, width, height, ...) {
  pngFile <- shiny::plotPNG(function() { expr }, width = width, height = height, ...)
  on.exit(unlink(pngFile))

  base64 <- httpuv::rawToBase64(readBin(pngFile, raw(1), file.size(pngFile)))
  paste0("data:image/png;base64,", base64)
}

legend_symbol <- makePlotURI({
  print(tric$key +
          theme(plot.background = element_rect(fill = NA, color = NA)) +
          labs(L = '0-2', T = '3-4', R = '5-8'))
}, 200, 200, bg = "transparent")

df <- data.frame(
  lng = 30,
  lat = 70,
  plot = legend_symbol,
  stringsAsFactors = FALSE
)

euro_example %>%
  st_transform(crs = 4326) %>%
  leaflet() %>%
  addProviderTiles(providers$Esri.WorldGrayCanvas) %>%
  addPolygons(smoothFactor = 0.1, weight = 0,
              fillColor = euro_example$rgb,
              fillOpacity = 1,
              popup =
                paste0(
                  '<b>', euro_example$name, '</b></br>',
                  'Primary: ',
                  formatC(euro_example$ed_0to2*100,
                          digits = 1, format = 'f'), '%</br>',
                  'Secondary: ',
                  formatC(euro_example$ed_3to4*100,
                          digits = 1, format = 'f'), '%</br>',
                  'Tertiary: ',
                  formatC(euro_example$ed_5to8*100,
                          digits = 1, format = 'f'), '%</br>'
                )
  ) %>%
  addMarkers(data = df, icon = ~icons(plot))



================================================
FILE: vignettes/choropleth_maps_with_tricolore.Rmd
================================================
---
title: "Choropleth maps with tricolore"
author: "Jonas Schöley"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Choropleth maps with tricolore}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
  %\VignetteDepends{shiny, sf, leaflet, tricolore, dplyr, ggplot2, ggtern, httpuv}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  tidy = FALSE,
  comment = "#>",
  fig.width = 6, fig.height = 6
)
```

Here I demonstrate how to use the `tricolore` library to generate ternary choropleth maps using both `ggplot2` and `leaflet`.

The data
--------

```{r}
library(tricolore)
```

The 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.

Take 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.

The 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.

`ggplot2` for ternary choropleth maps
-------------------------------------

Here I show how to create a choropleth map of the regional distribution of education attainment in Europe 2016 using `ggplot2`.

**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.**

```{r}
# color-code the data set and generate a color-key
tric <- Tricolore(euro_example, p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8')
```

`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.

```{r}
# add the vector of colors to the `euro_example` data
euro_example$rgb <- tric$rgb
```

**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.**

The 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`.

```{r}
library(ggplot2)

plot_educ <-
  # using sf dataframe `euro_example`...
  ggplot(euro_example) +
  # ...draw a polygon for each region...
  geom_sf(aes(fill = rgb, geometry = geometry), size = 0.1) +
  # ...and color each region according to the color code in the variable `rgb`
  scale_fill_identity()

plot_educ 
```

Using `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.

```{r}
library(ggtern)
plot_educ +
  annotation_custom(
    ggplotGrob(tric$key),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  )
```

Because the color key behaves just like a `ggplot2` plot we can change it to our liking.

```{r}
plot_educ <-
  plot_educ +
  annotation_custom(
    ggplotGrob(tric$key +
                 theme(plot.background = element_rect(fill = NA, color = NA)) +
                 labs(L = '0-2', T = '3-4', R = '5-8')),
    xmin = 55e5, xmax = 75e5, ymin = 8e5, ymax = 80e5
  )
plot_educ
```

Some final touches...

```{r}
plot_educ +
  theme_void() +
  coord_sf(datum = NA) +
  labs(
   title = 'European inequalities in educational attainment',
      subtitle = 'Regional distribution of ISCED education levels for people aged 25-64 in 2016.'
  )
```

`leaflet` for ternary choropleth maps
-------------------------------------

The `ggplot2` example above is easily adapted to `leaflet`. This time I use a continuous color scale.

```{r}
# color-code the data set and generate a color-key
tric <- Tricolore(euro_example, p1 = 'ed_0to2', p2 = 'ed_3to4', p3 = 'ed_5to8',
                  breaks = Inf)

# add the vector of colors to the `euro_example` data
euro_example$rgb <- tric$rgb
```

`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.

```{r}
library(sf)
library(leaflet)

euro_example %>%
  st_transform(crs = 4326) %>%
  leaflet() %>%
  addPolygons(smoothFactor = 0.1, weight = 0,
              fillColor = euro_example$rgb,
              fillOpacity = 1)
```

Adding a background map gives geographical context to the map. I also add a mouse pop-up of the actual data.

```{r}
euro_example %>%
  st_transform(crs = 4326) %>%
  leaflet() %>%
  addProviderTiles(providers$Esri.WorldTerrain) %>%
  addPolygons(smoothFactor = 0.1, weight = 0,
              fillColor = euro_example$rgb,
              fillOpacity = 1,
              popup =
                paste0(
                  '<b>', euro_example$name, '</b></br>',
                  'Primary: ',
                  formatC(euro_example$ed_0to2*100,
                          digits = 1, format = 'f'), '%</br>',
                  'Secondary: ',
                  formatC(euro_example$ed_3to4*100,
                          digits = 1, format = 'f'), '%</br>',
                  'Tertiary: ',
                  formatC(euro_example$ed_5to8*100,
                          digits = 1, format = 'f'), '%</br>'
                )
  )
```

Adding the legend to the leaflet map requires a bit of a [hack](https://github.com/rstudio/leaflet/issues/51#issuecomment-213108125).

```{r}
makePlotURI <- function(expr, width, height, ...) {
  pngFile <- shiny::plotPNG(function() { expr }, width = width, height = height, ...)
  on.exit(unlink(pngFile))

  base64 <- httpuv::rawToBase64(readBin(pngFile, raw(1), file.size(pngFile)))
  paste0("data:image/png;base64,", base64)
}

legend_symbol <- makePlotURI({
  print(tric$key +
          theme(plot.background = element_rect(fill = NA, color = NA)) +
          labs(L = '0-2', T = '3-4', R = '5-8'))
}, 200, 200, bg = "transparent")

df <- data.frame(
  lng = 30,
  lat = 70,
  plot = legend_symbol,
  stringsAsFactors = FALSE
)

euro_example %>%
  st_transform(crs = 4326) %>%
  leaflet() %>%
  addProviderTiles(providers$Esri.WorldGrayCanvas) %>%
  addPolygons(smoothFactor = 0.1, weight = 0,
              fillColor = euro_example$rgb,
              fillOpacity = 1,
              popup =
                paste0(
                  '<b>', euro_example$name, '</b></br>',
                  'Primary: ',
                  formatC(euro_example$ed_0to2*100,
                          digits = 1, format = 'f'), '%</br>',
                  'Secondary: ',
                  formatC(euro_example$ed_3to4*100,
                          digits = 1, format = 'f'), '%</br>',
                  'Tertiary: ',
                  formatC(euro_example$ed_5to8*100,
                          digits = 1, format = 'f'), '%</br>'
                )
  ) %>%
  addMarkers(data = df, icon = ~icons(plot))
```

Literature
----------

Brewer, 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.

Dorling, D. (2012). The Visualization of Spatial Social Structure. Chichester, UK: Wiley.

Schöley, J. (2021). The centered ternary balance scheme: A technique to visualize surfaces of unbalanced three-part compositions. Demographic Research (44).
Download .txt
gitextract_ffmohb3v/

├── .Rbuildignore
├── .github/
│   ├── .gitignore
│   └── workflows/
│       └── R-CMD-check.yaml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── CRAN-SUBMISSION
├── DESCRIPTION
├── LICENSE
├── NAMESPACE
├── NEWS.md
├── R/
│   ├── tricolore.R
│   └── zzz.R
├── README.Rmd
├── README.md
├── cran-comments.md
├── data/
│   ├── euro_basemap.RData
│   └── euro_example.RData
├── data-raw/
│   ├── euro_basemap.R
│   ├── euro_basemap.RData
│   ├── euro_example.R
│   └── euro_example.RData
├── inst/
│   ├── CITATION
│   └── shiny/
│       └── app.R
├── man/
│   ├── BasicKey.Rd
│   ├── BreaksAndLabels.Rd
│   ├── Centre.Rd
│   ├── ColorKeySextant.Rd
│   ├── ColorKeyTricolore.Rd
│   ├── ColorMapSextant.Rd
│   ├── ColorMapTricolore.Rd
│   ├── DemoTricolore.Rd
│   ├── GeometricMean.Rd
│   ├── Pertube.Rd
│   ├── PowerScale.Rd
│   ├── TernaryCenterGrid.Rd
│   ├── TernaryDistance.Rd
│   ├── TernaryLimits.Rd
│   ├── TernaryMeshCentroids.Rd
│   ├── TernaryMeshVertices.Rd
│   ├── TernaryNearest.Rd
│   ├── TernarySextantVertices.Rd
│   ├── TernarySurroundingSextant.Rd
│   ├── Tricolore.Rd
│   ├── TricoloreSextant.Rd
│   ├── ValidateMainArguments.Rd
│   ├── ValidateParametersShared.Rd
│   ├── ValidateParametersTricolore.Rd
│   ├── ValidateParametersTricoloreSextant.Rd
│   ├── euro_basemap.Rd
│   └── euro_example.Rd
├── tests/
│   ├── testthat/
│   │   └── test-global.R
│   └── testthat.R
└── vignettes/
    ├── choropleth_maps_with_tricolore.R
    └── choropleth_maps_with_tricolore.Rmd
Condensed preview — 55 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (184K chars).
[
  {
    "path": ".Rbuildignore",
    "chars": 199,
    "preview": "^.*\\.Rproj$\n^\\.Rproj\\.user$\npriv\nREADME_files\nREADME.md\nREADME.R\ndata-raw\nTODO.txt\nexamples\n^cran-comments\\.md$\nCODE_OF_"
  },
  {
    "path": ".github/.gitignore",
    "chars": 7,
    "preview": "*.html\n"
  },
  {
    "path": ".github/workflows/R-CMD-check.yaml",
    "chars": 1388,
    "preview": "# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples\n# Need help debugging build failures? Start at"
  },
  {
    "path": ".gitignore",
    "chars": 497,
    "preview": "# General ---------------------------------------------------------------------\n\npriv\n# R specific ---------------------"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "chars": 3348,
    "preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, w"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 4293,
    "preview": "Contributing to `tricolore`\n---------------------------\n\n*This guide is adapted from the `devtools` template*\n\nThe goal "
  },
  {
    "path": "CRAN-SUBMISSION",
    "chars": 91,
    "preview": "Version: 1.2.4\nDate: 2024-05-14 13:32:45 UTC\nSHA: c4f25b8a52e7e6ca54bf876796e1e0f9b4432a9e\n"
  },
  {
    "path": "DESCRIPTION",
    "chars": 1348,
    "preview": "Package: tricolore\nType: Package\nTitle: A Flexible Color Scale for Ternary Compositions\nVersion: 1.2.6\nAuthors@R: c(\n  p"
  },
  {
    "path": "LICENSE",
    "chars": 34916,
    "preview": "### GNU GENERAL PUBLIC LICENSE\n\nVersion 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc.\n<https://fsf."
  },
  {
    "path": "NAMESPACE",
    "chars": 858,
    "preview": "# Generated by roxygen2: do not edit by hand\n\nexport(DemoTricolore)\nexport(Tricolore)\nexport(TricoloreSextant)\nimportFro"
  },
  {
    "path": "NEWS.md",
    "chars": 1661,
    "preview": "# 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.RDat"
  },
  {
    "path": "R/tricolore.R",
    "chars": 43367,
    "preview": "# Misc --------------------------------------------------------------------\n\n# from nnet::which.is.max()\nMaxIndex <- fun"
  },
  {
    "path": "R/zzz.R",
    "chars": 110,
    "preview": ".onAttach <- function(...) {\n\n  packageStartupMessage('Please cite tricolore. See citation(\"tricolore\").')\n\n}\n"
  },
  {
    "path": "README.Rmd",
    "chars": 11697,
    "preview": "---\ntitle: \"tricolore. A flexible color scale for ternary compositions\"\noutput: github_document\n---\n\n```{r echo=FALSE}\nk"
  },
  {
    "path": "README.md",
    "chars": 12192,
    "preview": "<img src=\"inst/figures/tricolore.png\" align=\"right\" width=\"150\" height=\"174\" />tricolore. A flexible color scale for ter"
  },
  {
    "path": "cran-comments.md",
    "chars": 748,
    "preview": "This submission fixes CRAN check ERRORs which arose due to the 4.0.0 update of the ggtern import and were ultimately rel"
  },
  {
    "path": "data-raw/euro_basemap.R",
    "chars": 857,
    "preview": "#'---\n#' title: A flat and simplified map of Europe\n#' author: Jonas Schöley\n#' date: 2018-08-28\n#'---\n\nlibrary(tidyvers"
  },
  {
    "path": "data-raw/euro_example.R",
    "chars": 5876,
    "preview": "#'---\n#' title: Geodata for European NUTS-2 regions with added variables\n#' author: Jonas Schöley\n#' date: 2019-07-19\n#'"
  },
  {
    "path": "inst/CITATION",
    "chars": 1190,
    "preview": "citHeader('To cite tricolore in publications, please use:')\n\nbibentry(\n  bibtype = 'Article',\n  author = c(person('Jonas"
  },
  {
    "path": "inst/shiny/app.R",
    "chars": 6937,
    "preview": "library(shiny)\nlibrary(sf)\nlibrary(ggtern)\nlibrary(tricolore)\n\n# UI ----------------------------------------------------"
  },
  {
    "path": "man/BasicKey.Rd",
    "chars": 842,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{BasicKey}\n\\alias{BasicKe"
  },
  {
    "path": "man/BreaksAndLabels.Rd",
    "chars": 869,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{BreaksAndLabels}\n\\alias{"
  },
  {
    "path": "man/Centre.Rd",
    "chars": 994,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{Centre}\n\\alias{Centre}\n\\"
  },
  {
    "path": "man/ColorKeySextant.Rd",
    "chars": 1127,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ColorKeySextant}\n\\alias{"
  },
  {
    "path": "man/ColorKeyTricolore.Rd",
    "chars": 1530,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ColorKeyTricolore}\n\\alia"
  },
  {
    "path": "man/ColorMapSextant.Rd",
    "chars": 1027,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ColorMapSextant}\n\\alias{"
  },
  {
    "path": "man/ColorMapTricolore.Rd",
    "chars": 1466,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ColorMapTricolore}\n\\alia"
  },
  {
    "path": "man/DemoTricolore.Rd",
    "chars": 414,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{DemoTricolore}\n\\alias{De"
  },
  {
    "path": "man/GeometricMean.Rd",
    "chars": 657,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{GeometricMean}\n\\alias{Ge"
  },
  {
    "path": "man/Pertube.Rd",
    "chars": 1136,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{Pertube}\n\\alias{Pertube}"
  },
  {
    "path": "man/PowerScale.Rd",
    "chars": 814,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{PowerScale}\n\\alias{Power"
  },
  {
    "path": "man/TernaryCenterGrid.Rd",
    "chars": 685,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryCenterGrid}\n\\alia"
  },
  {
    "path": "man/TernaryDistance.Rd",
    "chars": 858,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryDistance}\n\\alias{"
  },
  {
    "path": "man/TernaryLimits.Rd",
    "chars": 668,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryLimits}\n\\alias{Te"
  },
  {
    "path": "man/TernaryMeshCentroids.Rd",
    "chars": 895,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryMeshCentroids}\n\\a"
  },
  {
    "path": "man/TernaryMeshVertices.Rd",
    "chars": 1013,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryMeshVertices}\n\\al"
  },
  {
    "path": "man/TernaryNearest.Rd",
    "chars": 722,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernaryNearest}\n\\alias{T"
  },
  {
    "path": "man/TernarySextantVertices.Rd",
    "chars": 707,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernarySextantVertices}\n"
  },
  {
    "path": "man/TernarySurroundingSextant.Rd",
    "chars": 789,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TernarySurroundingSextan"
  },
  {
    "path": "man/Tricolore.Rd",
    "chars": 2595,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{Tricolore}\n\\alias{Tricol"
  },
  {
    "path": "man/TricoloreSextant.Rd",
    "chars": 2091,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{TricoloreSextant}\n\\alias"
  },
  {
    "path": "man/ValidateMainArguments.Rd",
    "chars": 664,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ValidateMainArguments}\n\\"
  },
  {
    "path": "man/ValidateParametersShared.Rd",
    "chars": 376,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ValidateParametersShared"
  },
  {
    "path": "man/ValidateParametersTricolore.Rd",
    "chars": 376,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ValidateParametersTricol"
  },
  {
    "path": "man/ValidateParametersTricoloreSextant.Rd",
    "chars": 411,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\name{ValidateParametersTricol"
  },
  {
    "path": "man/euro_basemap.Rd",
    "chars": 576,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\docType{data}\n\\name{euro_base"
  },
  {
    "path": "man/euro_example.Rd",
    "chars": 1860,
    "preview": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/tricolore.R\n\\docType{data}\n\\name{euro_exam"
  },
  {
    "path": "tests/testthat/test-global.R",
    "chars": 4393,
    "preview": "context('test-global.R')\n\ntest_that('GeometricMean() works', {\n  expect_equal(GeometricMean(0:4), exp(mean(log(1:4))))\n "
  },
  {
    "path": "tests/testthat.R",
    "chars": 62,
    "preview": "library(testthat)\nlibrary(tricolore)\n\ntest_check('tricolore')\n"
  },
  {
    "path": "vignettes/choropleth_maps_with_tricolore.R",
    "chars": 4990,
    "preview": "## ----setup, include = FALSE---------------------------------------------------\nknitr::opts_chunk$set(\n  collapse = TRU"
  },
  {
    "path": "vignettes/choropleth_maps_with_tricolore.Rmd",
    "chars": 8737,
    "preview": "---\ntitle: \"Choropleth maps with tricolore\"\nauthor: \"Jonas Schöley\"\ndate: \"`r Sys.Date()`\"\noutput: rmarkdown::html_vigne"
  }
]

// ... and 4 more files (download for full content)

About this extraction

This page contains the full source code of the jschoeley/tricolore GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 55 files (171.8 KB), approximately 48.7k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!