---
title: "User Guide: 3 Plotting transformed data"
subtitle: "'ggspectra' `r packageVersion('ggspectra')`"
author: "Pedro J. Aphalo"
date: "`r Sys.Date()`"
output: 
  rmarkdown::html_vignette:
    toc: yes
vignette: >
  %\VignetteIndexEntry{User Guide: 3 Plotting transformed data}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

## Introduction

Package `ggspectra` extends `ggplot2` with stats, geoms, scales and annotations suitable for light spectra. It also defines `ggplot()` and  `autoplot()` methods specialized for the classes defined in package `photobiology` for storing different types of spectral data. The `autoplot()` methods are described separately in vignette 'Autoplot Methods'.

The new elements can be freely combined with methods and functions defined in packages `ggplot2`, `scales`, `ggrepel` and `cowplot`.

This third part of the User Guide describes how to combine manipulation of spectral data with plotting. This streamlined coding is made possible by the enhancement implemented in 'ggspectra' (>= 0.3.5) and in addition some of the examples make use of methods available only in 'photobiology' (>= 0.9.30).

In 'ggspectra' (>= 0.3.5) the data member of `gg` (ggplot) objects remains as an object of the classes for spectral data defined in 'photobiology' instead as being converted into a plain `data.frame`. This makes it possible some data manipulations to be done with methods specific to spectral data.

## Set up 

```{r}
library(ggplot2)
library(dplyr)
library(rlang)
library(photobiology)
library(photobiologyWavebands)
library(ggspectra)

good_label_repel <- packageVersion('ggrepel') != "0.8.0" #||
#  packageVersion('ggplot2') >= "3.1.0"

```

```{r, include=FALSE, echo=FALSE}
library(knitr)
opts_chunk$set(fig.align = 'center', 
               fig.show = 'hold', fig.width = 7, fig.height = 4,
               cache = FALSE)
options(warnPartialMatchArgs = FALSE)
```

Create a collection of two source_spct objects.

```{r}
two_suns.mspct <- source_mspct(list(sun1 = sun.spct, sun2 = sun.spct / 2))
```

We bind the two spectra in the collection into a single spectral object. This object
includes an indexing factor, by default names `spct.idx`. We use this new object to 
later on demonstrate grouping in ggplots.

```{r}
two_suns.spct <- rbindspct(two_suns.mspct)
```

We change the default theme.

```{r}
theme_set(theme_bw())
```

## Visualizing the effect of methods

As from version 0.3.5 the class of the spectral object stored by `ggplot()` is
no longer stripped, data transformations in layers can use methods from package
'photobiology' that expect spectral objects as input. A simple example of
spectral data smoothing follows.

```{r, eval=FALSE}
ggplot() + 
  geom_line(data = sun.spct, mapping = aes(w.length, s.e.irrad)) + 
  geom_line(data = sun.spct %>% smooth_spct(method = "supsmu"), 
            mapping = aes(w.length, s.e.irrad), 
            colour = "red", size = 1.2)
```

Can be now simplified because `.` refers to a `data` member of class `source_spct` while the automatic mapping remains valid because `smooth_spct()` returns a new `source_spct` object with the same column names as `sun.spct`. 

```{r}
ggplot(sun.spct) + 
  geom_line() + 
  geom_line(data = . %>% smooth_spct(method = "supsmu"), 
            colour = "red", size = 1.2)
```

The easiest way of plotting photon spectral irardiance instead of spectral energy irradiance is to temporarily change the default radiation unit.

```{r}
photon_as_default()
ggplot(sun.spct) + 
  geom_line() + 
  geom_line(data = . %>% smooth_spct(method = "supsmu"), 
            colour = "red", size = 1.2)
unset_radiation_unit_default()
```

Of course the default data does not need to be plotted, so this provides a roundabout way of applying methods,

```{r, eval=FALSE}
ggplot(sun.spct) + 
  geom_line(data = . %>% smooth_spct(method = "supsmu"), 
            colour = "red", size = 1.2)
```
 
which is equivalent to doing the transformation ahead of plotting, which might be preferable.
 
```{r, eval=FALSE}
sun.spct %>% 
  smooth_spct(method = "supsmu") %>%
  ggplot() + 
  geom_line(colour = "red", size = 1.2)
```

However, when using different transformations in different layers we need to apply them at each layer. 

```{r}
ggplot(sun.spct) + 
  geom_line() + 
  geom_line(data = . %>% smooth_spct(method = "custom"), 
            colour = "blue", size = 1) +
  geom_line(data = . %>% smooth_spct(method = "lowess"), 
            colour = "green", size = 1) +
  geom_line(data = . %>% smooth_spct(method = "supsmu"), 
            colour = "red", size = 1)
```

Of course, this approach works both with _geoms_ and _stats_, but one should remember that these layer functions do not "see" the original data object, but instead a new data frame containing the mapped variables in columns named according to _aesthetics_. The next example demostrates this and illustrates that smoothing displaces the wavelength of maximum spectral irradiance.

```{r}
ggplot(sun.spct) + 
  geom_line() + 
  stat_peaks(colour = "green", span = NULL) +
  geom_line(data = . %>% smooth_spct(method = "supsmu"), 
            colour = "red", size = 1.2) +
  stat_peaks(data = . %>% smooth_spct(method = "supsmu"),
             colour = "green", span = NULL)
```

We can easily highlight a wavelength region.

```{r}
ggplot(sun.spct) + 
  geom_line() + 
  geom_line(data = . %>% trim_wl(range = PAR()), colour = "red")
```

```{r}
ggplot(sun.spct) + 
  geom_line() + 
  geom_point(data = . %>% 
              trim_wl(range = PAR()) %>% tag(),
            mapping = aes(color = wl.color),
            shape = "circle", size = 1.3) +
  scale_color_identity()
```

```{r}
ggplot(sun.spct) + 
  geom_area(data = . %>% 
              trim_wl(range = VIS()) %>% 
              tag(w.band = VIS_bands()),
            mapping = aes(fill = wb.color)) +
  geom_line() + 
  scale_fill_identity()
```
