diff --git a/.circleci/config.yml b/.circleci/config.yml
index 6930fdef..07886146 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -26,7 +26,7 @@ jobs:
command: |
sudo apt-get install -y pandoc libudunits2-dev libgdal-dev libxt-dev libglu1-mesa-dev libfftw3-dev libglpk40 libxml2-dev libcurl4-openssl-dev apt-transport-https software-properties-common
sudo R -e 'install.packages(c("curl", "devtools", "mvtnorm", "hexbin", "tidyverse", "tidymodels", "kknn", "kernlab", "pracma", "reshape2", "ggplot2", "datasets", "fastDummies")); devtools::install_github("ropensci/plotly"); devtools::install_github("johannesbjork/LaCroixColoR"); install.packages("BiocManager"); BiocManager::install("EBImage"); devtools::install_deps(dependencies = TRUE) '
- sudo R -e 'install.packages("https://github.com/hypertidy/anglr/archive/refs/tags/v0.7.0.tar.gz", repos=NULL, type="source"); devtools::install_deps(dependencies = TRUE) '
+ sudo R -e 'install.packages("https://github.com/hypertidy/anglr/archive/refs/tags/v0.7.0.tar.gz", repos=NULL, type="source", dependencies = TRUE); devtools::install_deps(dependencies = TRUE) '
- save_cache:
key: cache4
paths:
diff --git a/r/2021-07-27-ml-pca.rmd b/r/2021-07-27-ml-pca.rmd
new file mode 100644
index 00000000..e5623c05
--- /dev/null
+++ b/r/2021-07-27-ml-pca.rmd
@@ -0,0 +1,351 @@
+## PCA Visualization in Python
+Visualize Principle Component Analysis (PCA) of your high-dimensional data in R with Plotly.
+
+This page first shows how to visualize higher dimension data using various Plotly figures combined with dimensionality reduction (aka projection). Then, we dive into the specific details of our projection algorithm.
+
+We will use [Tidymodels](https://www.tidymodels.org/) or [Caret](https://cran.r-project.org/web/packages/caret/vignettes/caret.html#) to load one of the datasets, and apply dimensionality reduction. Tidymodels is a popular Machine Learning (ML) library that offers various tools for creating and training ML algorithms, feature engineering, data cleaning, and evaluating and testing models.
+
+
+## High-dimensional PCA Analysis with `splom`
+
+The dimensionality reduction technique we will be using is called the [Principal Component Analysis (PCA)](https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/prcomp). It is a powerful technique that arises from linear algebra and probability theory. In essence, it computes a matrix that represents the variation of your data ([covariance matrix/eigenvectors][covmatrix]), and rank them by their relevance (explained variance/eigenvalues).
+
+[covmatrix]: https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues#:~:text=As%20it%20is%20a%20square%20symmetric%20matrix%2C%20it%20can%20be%20diagonalized%20by%20choosing%20a%20new%20orthogonal%20coordinate%20system%2C%20given%20by%20its%20eigenvectors%20(incidentally%2C%20this%20is%20called%20spectral%20theorem)%3B%20corresponding%20eigenvalues%20will%20then%20be%20located%20on%20the%20diagonal.%20In%20this%20new%20coordinate%20system%2C%20the%20covariance%20matrix%20is%20diagonal%20and%20looks%20like%20that%3A
+
+
+### Visualize all the original dimensions
+
+First, let's plot all the features and see how the `species` in the Iris dataset are grouped. In a [Scatter Plot Matrix (splom)](https://plot.ly/r/splom/), each subplot displays a feature against another, so if we have $N$ features we have a $N \times N$ matrix.
+
+In our example, we are plotting all 4 features from the Iris dataset, thus we can see how `sepal_width` is compared against `sepal_length`, then against `petal_width`, and so forth. Keep in mind how some pairs of features can more easily separate different species.
+
+```{r}
+library(plotly)
+
+data(iris)
+
+axis = list(showline=FALSE,
+ zeroline=FALSE,
+ gridcolor='#ffff',
+ ticklen=4,
+ titlefont=list(size=13))
+
+
+fig <- iris %>%
+ plot_ly()
+fig <- fig %>%
+ add_trace(
+ type = 'splom',
+ dimensions = list(
+ list(label='sepal length', values=~Sepal.Length),
+ list(label='sepal width', values=~Sepal.Width),
+ list(label='petal length', values=~Petal.Length),
+ list(label='petal width', values=~Petal.Width)
+ ),
+ color = ~Species, colors = c('#636EFA','#EF553B','#00CC96') ,
+ marker = list(
+ size = 7,
+ line = list(
+ width = 1,
+ color = 'rgb(230,230,230)'
+ )
+ )
+ )
+fig <- fig %>% style(diagonal = list(visible = FALSE))
+fig <- fig %>%
+ layout(
+ hovermode='closest',
+ dragmode= 'select',
+ plot_bgcolor='rgba(240,240,240, 0.95)',
+ xaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
+ yaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
+ xaxis2=axis,
+ xaxis3=axis,
+ xaxis4=axis,
+ yaxis2=axis,
+ yaxis3=axis,
+ yaxis4=axis
+ )
+
+fig
+```
+
+
+### Visualize all the principal components
+
+Now, we apply `PCA` the same dataset, and retrieve **all** the components. We use the same `splom` trace to display our results, but this time our features are the resulting *principal components*, ordered by how much variance they are able to explain.
+
+The importance of explained variance is demonstrated in the example below. The subplot between PC3 and PC4 is clearly unable to separate each class, whereas the subplot between PC1 and PC2 shows a clear separation between each species.
+
+```{r}
+library(plotly)
+library(stats)
+data(iris)
+X <- subset(iris, select = -c(Species))
+prin_comp <- prcomp(X)
+explained_variance_ratio <- summary(prin_comp)[["importance"]]['Proportion of Variance',]
+explained_variance_ratio <- 100 * explained_variance_ratio
+components <- prin_comp[["x"]]
+components <- data.frame(components)
+components <- cbind(components, iris$Species)
+components$PC3 <- -components$PC3
+components$PC2 <- -components$PC2
+
+axis = list(showline=FALSE,
+ zeroline=FALSE,
+ gridcolor='#ffff',
+ ticklen=4,
+ titlefont=list(size=13))
+
+fig <- components %>%
+ plot_ly() %>%
+ add_trace(
+ type = 'splom',
+ dimensions = list(
+ list(label=paste('PC 1 (',toString(round(explained_variance_ratio[1],1)),'%)',sep = ''), values=~PC1),
+ list(label=paste('PC 2 (',toString(round(explained_variance_ratio[2],1)),'%)',sep = ''), values=~PC2),
+ list(label=paste('PC 3 (',toString(round(explained_variance_ratio[3],1)),'%)',sep = ''), values=~PC3),
+ list(label=paste('PC 4 (',toString(round(explained_variance_ratio[4],1)),'%)',sep = ''), values=~PC4)
+ ),
+ color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96')
+ ) %>%
+ style(diagonal = list(visible = FALSE)) %>%
+ layout(
+ legend=list(title=list(text='color')),
+ hovermode='closest',
+ dragmode= 'select',
+ plot_bgcolor='rgba(240,240,240, 0.95)',
+ xaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
+ yaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
+ xaxis2=axis,
+ xaxis3=axis,
+ xaxis4=axis,
+ yaxis2=axis,
+ yaxis3=axis,
+ yaxis4=axis
+ )
+
+fig
+```
+
+
+### Visualize a subset of the principal components
+
+When you will have too many features to visualize, you might be interested in only visualizing the most relevant components. Those components often capture a majority of the [explained variance](https://en.wikipedia.org/wiki/Explained_variation), which is a good way to tell if those components are sufficient for modelling this dataset.
+
+In the example below, our dataset contains 10 features, but we only select the first 4 components, since they explain 99% of the total variance.
+
+```{r}
+library(plotly)
+library(stats)
+library(MASS)
+
+db = Boston
+
+prin_comp <- prcomp(db, rank. = 4)
+
+components <- prin_comp[["x"]]
+components <- data.frame(components)
+components <- cbind(components, db$medv)
+components$PC2 <- -components$PC2
+colnames(components)[5] = 'Median_Price'
+
+tot_explained_variance_ratio <- summary(prin_comp)[["importance"]]['Proportion of Variance',]
+tot_explained_variance_ratio <- 100 * sum(tot_explained_variance_ratio)
+
+tit = 'Total Explained Variance = 99.56'
+
+axis = list(showline=FALSE,
+ zeroline=FALSE,
+ gridcolor='#ffff',
+ ticklen=4)
+
+fig <- components %>%
+ plot_ly() %>%
+ add_trace(
+ type = 'splom',
+ dimensions = list(
+ list(label='PC1', values=~PC1),
+ list(label='PC2', values=~PC2),
+ list(label='PC3', values=~PC3),
+ list(label='PC4', values=~PC4)
+ ),
+ color=~Median_Price,
+ marker = list(
+ size = 7
+ )
+ ) %>% style(diagonal = list(visible = F)) %>%
+ layout(
+ title= tit,
+ hovermode='closest',
+ dragmode= 'select',
+ plot_bgcolor='rgba(240,240,240, 0.95)',
+ xaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
+ yaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
+ xaxis2=axis,
+ xaxis3=axis,
+ xaxis4=axis,
+ yaxis2=axis,
+ yaxis3=axis,
+ yaxis4=axis
+ )
+options(warn=-1)
+fig
+```
+
+
+## 2D PCA Scatter Plot
+
+In the previous examples, you saw how to visualize high-dimensional PCs. In this example, we show you how to simply visualize the first two principal components of a PCA, by reducing a dataset of 4 dimensions to 2D.
+
+```{r}
+library(plotly)
+library(stats)
+data(iris)
+X <- subset(iris, select = -c(Species))
+prin_comp <- prcomp(X, rank. = 2)
+components <- prin_comp[["x"]]
+components <- data.frame(components)
+components <- cbind(components, iris$Species)
+components$PC2 <- -components$PC2
+
+fig <- plot_ly(components, x = ~PC1, y = ~PC2, color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96'), type = 'scatter', mode = 'markers')%>%
+ layout(
+ legend=list(title=list(text='color')),
+ xaxis = list(
+ title = "0"),
+ yaxis = list(
+ title = "1"))
+fig
+```
+
+
+## Visualize PCA with scatter3d
+
+With scatter3d, you can visualize an additional dimension, which let you capture even more variance.
+
+```{r}
+data("iris")
+
+X <- subset(iris, select = -c(Species))
+
+prin_comp <- prcomp(X, rank. = 3)
+
+components <- prin_comp[["x"]]
+components <- data.frame(components)
+components$PC2 <- -components$PC2
+components$PC3 <- -components$PC3
+components = cbind(components, iris$Species)
+
+tot_explained_variance_ratio <- summary(prin_comp)[["importance"]]['Proportion of Variance',]
+tot_explained_variance_ratio <- 100 * sum(tot_explained_variance_ratio)
+
+tit = 'Total Explained Variance = 99.48'
+
+fig <- plot_ly(components, x = ~PC1, y = ~PC2, z = ~PC3, color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96') ) %>%
+ add_markers(size = 12)
+
+
+fig <- fig %>%
+ layout(
+ title= tit)
+
+fig
+```
+
+
+## Plotting explained variance
+
+Often, you might be interested in seeing how much variance PCA is able to explain as you increase the number of components, in order to decide how many dimensions to ultimately keep or analyze. This example shows you how to quickly plot the cumulative sum of explained variance for a high-dimensional dataset like [PimaIndiansDiabetes](https://rdrr.io/cran/mlbench/man/PimaIndiansDiabetes.html).
+
+With a higher explained variance, you are able to capture more variability in your dataset, which could potentially lead to better performance when training your model. For a more mathematical explanation, see this [Q&A thread](https://stats.stackexchange.com/questions/22569/pca-and-proportion-of-variance-explained).
+
+```{r}
+library(plotly)
+library(stats)
+library(base)
+library(mlbench)
+data(PimaIndiansDiabetes)
+
+X <- subset(PimaIndiansDiabetes, select = -c(diabetes))
+prin_comp <- prcomp(X)
+explained_variance_ratio <- summary(prin_comp)[["importance"]]['Proportion of Variance',]
+cumsum <- cumsum(explained_variance_ratio)
+data <- data.frame(cumsum,seq(1, length(cumsum), 1))
+colnames(data) <- c('Explained_Variance','Components')
+
+fig <- plot_ly(data = data, x = ~Components, y = ~Explained_Variance, type = 'scatter', mode = 'lines', fill = 'tozeroy') %>%
+ layout(
+ xaxis = list(
+ title = "# Components", tickvals = seq(1, length(cumsum), 1)),
+ yaxis = list(
+ title = "Explained Variance"))
+fig
+```
+
+
+## Visualize Loadings
+
+It is also possible to visualize loadings using `shapes`, and use `annotations` to indicate which feature a certain loading original belong to. Here, we define loadings as:
+
+$$
+loadings = eigenvectors \cdot \sqrt{eigenvalues}
+$$
+
+For more details about the linear algebra behind eigenvectors and loadings, see this [Q&A thread](https://stats.stackexchange.com/questions/143905/loadings-vs-eigenvectors-in-pca-when-to-use-one-or-another).
+
+```{r}
+library(plotly)
+library(stats)
+data(iris)
+X <- subset(iris, select = -c(Species))
+prin_comp <- prcomp(X, rank = 2)
+components <- prin_comp[["x"]]
+components <- data.frame(components)
+components <- cbind(components, iris$Species)
+components$PC2 <- -components$PC2
+explained_variance <- summary(prin_comp)[["sdev"]]
+explained_variance <- explained_variance[1:2]
+comp <- prin_comp[["rotation"]]
+comp[,'PC2'] <- - comp[,'PC2']
+loadings <- comp
+for (i in seq(explained_variance)){
+ loadings[,i] <- comp[,i] * explained_variance[i]
+}
+
+features = c('sepal_length', 'sepal_width', 'petal_length', 'petal_width')
+
+fig <- plot_ly(components, x = ~PC1, y = ~PC2, color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96'), type = 'scatter', mode = 'markers')%>%
+ layout(
+ legend=list(title=list(text='color')),
+ xaxis = list(
+ title = "0"),
+ yaxis = list(
+ title = "1"))
+for (i in seq(4)){
+ fig <- fig %>%
+ add_segments(x = 0, xend = loadings[i, 1], y = 0, yend = loadings[i, 2], line = list(color = 'black'),inherit = FALSE, showlegend = FALSE) %>%
+ add_annotations(x=loadings[i, 1], y=loadings[i, 2], ax = 0, ay = 0,text = features[i], xanchor = 'center', yanchor= 'bottom')
+}
+
+fig
+```
+
+
+## References
+
+Learn more about `scatter3d`, and `splom` here:
+
+* https://plot.ly/r/3d-scatter-plots/
+
+* https://plot.ly/r/splom/
+
+The following resources offer an in-depth overview of PCA and explained variance:
+
+* https://en.wikipedia.org/wiki/Explained_variation
+
+* https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues/140579#140579
+
+* https://stats.stackexchange.com/questions/143905/loadings-vs-eigenvectors-in-pca-when-to-use-one-or-another
+
+* https://stats.stackexchange.com/questions/22569/pca-and-proportion-of-variance-explained
diff --git a/r/2021-07-28-ml-tsne-umap.rmd b/r/2021-07-28-ml-tsne-umap.rmd
new file mode 100644
index 00000000..bdfee5ca
--- /dev/null
+++ b/r/2021-07-28-ml-tsne-umap.rmd
@@ -0,0 +1,190 @@
+## t-SNE and UMAP projections in Python
+
+This page presents various ways to visualize two popular dimensionality reduction techniques, namely the [t-distributed stochastic neighbor embedding](https://lvdmaaten.github.io/tsne/) (t-SNE) and [Uniform Manifold Approximation and Projection](https://umap-learn.readthedocs.io/en/latest/index.html) (UMAP). They are needed whenever you want to visualize data with more than two or three features (i.e. dimensions).
+
+We first show how to visualize data with more than three features using the [scatter plot matrix](https://plotly.com/r/splom/#:~:text=The%20Plotly%20splom%20trace%20implementation,array%2Fvariable%20represents%20a%20dimension), then we apply dimensionality reduction techniques to get 2D/3D representation of our data, and visualize the results with [scatter plots](https://plotly.com/r/line-and-scatter/) and [3D scatter plots](https://plotly.com/r/3d-scatter-plots/).
+
+
+## Basic t-SNE projections
+
+t-SNE is a popular dimensionality reduction algorithm that arises from probability theory. Simply put, it projects the high-dimensional data points (sometimes with hundreds of features) into 2D/3D by inducing the projected data to have a similar distribution as the original data points by minimizing something called the [KL divergence](https://towardsdatascience.com/light-on-math-machine-learning-intuitive-guide-to-understanding-kl-divergence-2b382ca2b2a8).
+
+Compared to a method like Principal Component Analysis (PCA), it takes significantly more time to converge, but present significantly better insights when visualized. For example, by projecting features of a flowers, it will be able to distinctly group
+
+
+### Visualizing high-dimensional data with `splom`
+
+First, let's try to visualize every feature of the [Iris dataset](https://archive.ics.uci.edu/ml/datasets/iris), and color everything by the species. We will use the Scatter Plot Matrix ([splom](https://plotly.com/r/splom/#:~:text=The%20Plotly%20splom%20trace%20implementation,array%2Fvariable%20represents%20a%20dimension)), which lets us plot each feature against everything else, which is convenient when your dataset has more than 3 dimensions.
+
+```{r}
+library(plotly)
+library(stats)
+data(iris)
+X <- subset(iris, select = -c(Species))
+axis = list(showline=FALSE,
+ zeroline=FALSE,
+ gridcolor='#ffff',
+ ticklen=4)
+fig <- iris %>%
+ plot_ly() %>%
+ add_trace(
+ type = 'splom',
+ dimensions = list(
+ list(label = 'sepal_width',values=~Sepal.Width),
+ list(label = 'sepal_length',values=~Sepal.Length),
+ list(label ='petal_width',values=~Petal.Width),
+ list(label = 'petal_length',values=~Petal.Length)),
+ color = ~Species, colors = c('#636EFA','#EF553B','#00CC96')
+ )
+fig <- fig %>%
+ layout(
+ legend=list(title=list(text='species')),
+ hovermode='closest',
+ dragmode= 'select',
+ plot_bgcolor='rgba(240,240,240,0.95)',
+ xaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
+ yaxis=list(domain=NULL, showline=F, zeroline=F, gridcolor='#ffff', ticklen=4),
+ xaxis2=axis,
+ xaxis3=axis,
+ xaxis4=axis,
+ yaxis2=axis,
+ yaxis3=axis,
+ yaxis4=axis
+ )
+fig
+
+```
+
+### Project data into 2D with t-SNE and `px.scatter`
+
+Now, let's use the t-SNE algorithm to project the data shown above into two dimensions. Notice how each of the species is physically separate from each other.
+
+```{r}
+library(tsne)
+library(plotly)
+data("iris")
+
+features <- subset(iris, select = -c(Species))
+
+set.seed(0)
+tsne <- tsne(features, initial_dims = 2)
+tsne <- data.frame(tsne)
+pdb <- cbind(tsne,iris$Species)
+options(warn = -1)
+fig <- plot_ly(data = pdb ,x = ~X1, y = ~X2, type = 'scatter', mode = 'markers', split = ~iris$Species)
+fig
+
+```
+
+### Project data into 3D with t-SNE and `px.scatter_3d`
+
+t-SNE can reduce your data to any number of dimensions you want! Here, we show you how to project it to 3D and visualize with a 3D scatter plot.
+
+```{r}
+library(tsne)
+library(plotly)
+data("iris")
+
+features <- subset(iris, select = -c(Species))
+
+#set.seed(0)
+tsne <- tsne(features, initial_dims = 3, k =3)
+tsne <- data.frame(tsne)
+pdb <- cbind(tsne,iris$Species)
+options(warn = -1)
+fig <- plot_ly(data = pdb ,x = ~X1, y = ~X2, z = ~X3, color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96') ) %>%
+ add_markers(size = 8)
+fig
+
+```
+
+## Projections with UMAP
+
+Just like t-SNE, [UMAP](https://umap-learn.readthedocs.io/en/latest/index.html) is a dimensionality reduction specifically designed for visualizing complex data in low dimensions (2D or 3D). As the number of data points increase, UMAP becomes more time efficient compared to TSNE.
+
+In the example below, we see how easy it is to use UMAP in R.
+
+```{r}
+
+library(plotly)
+library(umap)
+iris.data = iris[, grep("Sepal|Petal", colnames(iris))]
+iris.labels = iris[, "Species"]
+iris.umap = umap(iris.data, n_components = 2, random_state = 15)
+layout <- iris.umap[["layout"]]
+layout <- data.frame(layout)
+final <- cbind(layout, iris$Species)
+
+fig <- plot_ly(final, x = ~X1, y = ~X2, color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96'), type = 'scatter', mode = 'markers')%>%
+ layout(
+ legend=list(title=list(text='species')),
+ xaxis = list(
+ title = "0"),
+ yaxis = list(
+ title = "1"))
+
+iris.umap = umap(iris.data, n_components = 3, random_state = 15)
+layout <- iris.umap[["layout"]]
+layout <- data.frame(layout)
+final <- cbind(layout, iris$Species)
+
+fig2 <- plot_ly(final, x = ~X1, y = ~X2, z = ~X3, color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96'))
+fig2 <- fig2 %>% add_markers()
+fig2 <- fig2 %>% layout(scene = list(xaxis = list(title = '0'),
+ yaxis = list(title = '1'),
+ zaxis = list(title = '2')))
+
+fig
+fig2
+```
+
+## Visualizing image datasets
+
+In the following example, we show how to visualize large image datasets using UMAP.
+
+Although there's over 1000 data points, and many more dimensions than the previous example, it is still extremely fast. This is because UMAP is optimized for speed, both from a theoretical perspective, and in the way it is implemented. Learn more in [this comparison post](https://umap-learn.readthedocs.io/en/latest/benchmarking.html).
+
+```{r}
+library(rsvd)
+library(plotly)
+library(umap)
+data('digits')
+digits.data = digits[, grep("pixel", colnames(digits))]
+digits.labels = digits[, "label"]
+digits.umap = umap(digits.data, n_components = 2, k = 10)
+layout <- digits.umap[["layout"]]
+layout <- data.frame(layout)
+final <- cbind(layout, digits[,'label'])
+colnames(final) <- c('X1', 'X2', 'label')
+
+fig <- plot_ly(final, x = ~X1, y = ~X2, split = ~label, type = 'scatter', mode = 'markers')%>%
+ layout(
+ legend=list(title=list(text='digit')),
+ xaxis = list(
+ title = "0"),
+ yaxis = list(
+ title = "1"))
+fig
+
+```
+
+
+## Reference
+
+Plotly figures:
+* https://plotly.com/r/line-and-scatter/
+
+* https://plotly.com/r/3d-scatter-plots/
+
+* https://plotly.com/r/splom/
+
+
+Details about algorithms:
+* UMAP library: https://umap-learn.readthedocs.io/en/latest/
+
+* t-SNE User guide: https://cran.r-project.org/web/packages/tsne/tsne.pdf
+
+* t-SNE paper: https://www.jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf
+
+* MNIST: http://yann.lecun.com/exdb/mnist/
+
diff --git a/r/2021-07-29-graphing-multiple-chart-types.rmd b/r/2021-07-29-graphing-multiple-chart-types.rmd
new file mode 100644
index 00000000..66067548
--- /dev/null
+++ b/r/2021-07-29-graphing-multiple-chart-types.rmd
@@ -0,0 +1,64 @@
+## Multiple Chart Types in R
+
+How to design figures with multiple chart types in R.
+
+### Chart Types versus Trace Types
+
+Plotly's figure data structure supports defining [subplots](https://plotly.com/r/subplots/) of [various types](https://plotly.com/r/mixed-subplots/) (e.g. [cartesian](https://plotly.com/r/axes/), [polar](https://plotly.com/r/polar-chart/), [3-dimensional](https://plotly.com/r/3d-charts/), [maps](https://plotly.com/r/maps/) etc) with attached traces of various compatible types (e.g. scatter, bar, choropleth, surface etc). This means that **Plotly figures are not constrained to representing a fixed set of "chart types"** such as scatter plots only or bar charts only or line charts only: any subplot can contain multiple traces of different types.
+
+
+### Multiple Trace Types with Plotly
+
+Figures produced with Plotly have the add_trace() method, so it is easy to start with a Plotly figure containing only traces of a given type, and add traces of another type.
+
+```{r}
+library(plotly)
+data <- data.frame(
+ Fruits = c ("apples", "bananas", "oranges"),
+ Line = c(1,3,2),
+ Bar = c(2,1,3))
+
+fig <- plot_ly(data , x = ~Fruits, y = ~Bar, type = 'bar', name = 'Last Year') %>%
+ add_trace(data , x = ~Fruits, y = ~Line, type = 'scatter', mode = 'lines', name = 'This year')
+
+fig <- fig %>% layout(yaxis = list(title = "Amount"))
+fig <- fig %>% layout(legend=list(title=list(text=' Time Period ')))
+fig
+```
+
+#### Line Chart and a Bar Chart
+
+```{r}
+library(plotly)
+data <- data.frame(
+ X = c (0, 1, 2, 3, 4, 5),
+ Line = c(1.5, 1, 1.3, 0.7, 0.8, 0.9),
+ Bar = c(1, 0.5, 0.7, -1.2, 0.3, 0.4))
+
+fig <- plot_ly(data , x = ~X, y = ~Bar, type = 'bar') %>%
+ add_trace(data , x = ~X, y = ~Line, type = 'scatter', mode = 'lines+markers')
+
+fig
+```
+
+#### A Contour and Scatter Plot of the Method of Steepest Descent
+
+```{r}
+library(plotly)
+library(jsonlite)
+urlfile<-'https://raw.githubusercontent.com/plotly/datasets/master/steepest.json'
+data<-fromJSON(url(urlfile))
+X <- data[["contour_x"]][,]
+Y <- data[["contour_y"]][,]
+Z <- data[["contour_z"]][,,]
+fig <- plot_ly() %>%
+ add_trace(x = X, y= Y, z = Z, type = "contour") %>%
+ hide_colorbar()%>% layout(showlegend = FALSE) %>%
+ add_trace(x = data$trace_x, y = data$trace_y, type = "scatter",
+ mode = "lines+markers", name = 'steepest', inherit = FALSE,
+ marker = list(color = 'black'), line = list(color = 'black'))
+fig
+```
+
+#### Reference
+See https://plotly.com/r/reference/ for more information and attribute options!
\ No newline at end of file
diff --git a/r/2021-08-02-styling-plotly-in-r.rmd b/r/2021-08-02-styling-plotly-in-r.rmd
new file mode 100644
index 00000000..bc78e46b
--- /dev/null
+++ b/r/2021-08-02-styling-plotly-in-r.rmd
@@ -0,0 +1,128 @@
+### Styling Figures made with Plotly
+
+Plotly's R graphing library makes it easy to create interactive, publication-quality graphs.
+
+More specifically, here are the 3 ways you can style and customize figures made with Plotly:
+
+1. Control common parameters like titles, labeling and colors using built-in Plotly function arguments
+2. Updating the plotly figure attributes
+3. Using ggplot2's template via theme attribute.
+
+### Built-in Plotly Styling Arguments
+
+Many common styling options can be set directly. Every Plotly function accepts the following arguments:
+
+- `title` to set the figure title
+- `labels` to override the default axis and legend labels behaviour, which is to use the data frame column name if available, and otherwise to use the label name itself like "x", "y", "color" etc. `labels` accepts list whose values are the desired labels. These labels appear in axis labels, legend and color bar titles, and in hover labels.
+- `category_orders` to override the default category ordering behaviour, which is to use the order in which the data appears in the input. `category_orders` accepts an array whose values are a `list` of values in the desired order. These orderings apply everywhere categories appear: in legends, on axes, in bar stacks, in the order of facets, in the order of animation frames etc.
+- `hoverformat` and `hoverinfo` to control which attributes appear in the hover label and how they are formatted.
+- Various color-related attributes such as `color`, `colors`, `colorbar` and `colorRampPalette` set the colors used in the figure.
+
+To illustrate each of these, here is a simple, default figure made with Plotly. Note the default orderings for the x-axis categories.
+
+```{r}
+library(reshape2)
+library(plotly)
+
+data("tips")
+
+fig1 <- plot_ly(tips, x = ~day, y = ~total_bill, type = 'bar', color = ~sex) %>%
+ layout( barmode = 'stack')
+options(warn = -1)
+fig1
+
+
+```
+
+Here is the same figure, restyled by adding some extra parameters to the initial Plotly function call:
+
+```{r}
+
+library(reshape2)
+library(plotly)
+
+data("tips")
+
+xform <- list(title = 'Day of Week',
+ categoryorder = "array",
+ categoryarray = c("Thur",
+ "Fri",
+ "Sat",
+ "Sun"))
+
+fig2 <- plot_ly(tips, x = ~day, y = ~total_bill, type = 'bar', color = ~sex, colors = c("#3399FF", "#FF6666")) %>%
+ layout( barmode = 'stack', xaxis = xform, yaxis = list(title = 'Sum of Receipts'), title = "Receipts by Payer Gender and Day of Week",
+ legend=list(title=list(text=' Payer Gender ')))
+fig2
+
+```
+
+### Updating or Modifying Figures made with Plotly
+
+
+Here is the same figure as above, with some additional customizations to the axes and legend.
+
+```{r}
+
+library(reshape2)
+library(plotly)
+
+data("tips")
+
+xform <- list(title = 'Day of Week',
+ categoryorder = "array",
+ categoryarray = c("Thur",
+ "Fri",
+ "Sat",
+ "Sun"))
+
+# add a text callout with arrow
+a <- list(
+ x = 'Fri',
+ y = 400,
+ text = 'Below Target !',
+ showarrow = TRUE,
+ arrowhead = 1,
+ ax = 20,
+ ay = -40
+)
+# the y-axis prefix given as dollars
+fig <- plot_ly(tips, x = ~day, y = ~total_bill, type = 'bar', color = ~sex, colors = c("#3399FF", "#FF6666")) %>%
+ layout( barmode = 'stack', xaxis = xform, yaxis = list(title = 'Sum of Receipts', tickprefix = '$'), title = "Receipts by Payer Gender and Day of Week")
+# customie legend orientation & position
+fig <- fig %>% layout(legend = list(x = 0.2, y = 1, orientation = 'h'))
+# add a horizontal "target" line
+fig <- fig %>% add_segments(x = 'Thur', xend = 0, y = 950, yend = 950,
+ line = list(dash = "dash", color = 'black'),inherit = FALSE, showlegend = FALSE)
+fig <- fig %>% layout(annotations = a)
+# customize font
+fig <- fig %>% layout(font = list(family = "Rockwell"))
+fig
+
+```
+
+### How ggplot2 Express Works with Templates
+
+In this example, we will be using a template for the color palette.
+
+```{r}
+
+library(ggplot2)
+library(plotly)
+data(mpg)
+base <- ggplot(mpg, aes(cty, hwy, color = factor(cyl))) +
+ geom_jitter() +
+ geom_abline(colour = "grey50", size = 2)
+labelled <- base +
+ labs(
+ x = "City mileage/gallon",
+ y = "Highway mileage/gallon",
+ colour = "Cylinders",
+ title = "Highway and city mileage are highly correlated"
+ ) +
+ scale_colour_brewer(type = "seq", palette = "Spectral")
+fig <- ggplotly(labelled)
+fig
+
+```
+
diff --git a/r/2021-08-03-horizontal-vertical-shapes.rmd b/r/2021-08-03-horizontal-vertical-shapes.rmd
new file mode 100644
index 00000000..1fd859cf
--- /dev/null
+++ b/r/2021-08-03-horizontal-vertical-shapes.rmd
@@ -0,0 +1,410 @@
+
+## Horizontal and Vertical Lines and Rectangles in R
+
+How to add annotated horizontal and vertical lines in R.
+
+### Horizontal and Vertical Lines and Rectangles
+
+Horizontal and vertical lines and rectangles that span an entire plot can be added via the `shapes` parameter of `layout`. Shapes added with these methods are added as [layout shapes](https://plotly.com/r/shapes/). These shapes are fixed to the endpoints of one axis, regardless of the range of the plot, and fixed to data coordinates on the other axis. The following shows some possibilities, try panning and zooming the resulting figure to see how the shapes stick to some axes:
+
+```{r}
+library(plotly)
+data("iris")
+
+hline <- function(y = 0, color = "black") {
+ list(
+ type = "line",
+ x0 = 0,
+ x1 = 1,
+ xref = "paper",
+ y0 = y,
+ y1 = y,
+ line = list(color = color)
+ )
+}
+
+fig <- plot_ly(data = iris, x = ~Petal.Length, y = ~Petal.Width,
+ type = 'scatter', mode = 'markers') %>%
+ layout(shapes = list(hline(0.9), list(type = "rect",line = list(color = "black"),
+ x0 = 0.9, x1 = 2)))
+fig
+```
+
+The shapes can also be filled with a specified color using `fillcolor` and the lines can also be changed to dotted lines using the `dash` parameter.
+
+```{r}
+library(plotly)
+data("iris")
+
+vline <- function(x = 0, color = "green") {
+ list(
+ type = "line",
+ y0 = 0,
+ y1 = 1,
+ yref = "paper",
+ x0 = x,
+ x1 = x,
+ line = list(color = color, dash="dot")
+ )
+}
+
+fig <- plot_ly(data = iris, x = ~Petal.Length, y = ~Petal.Width,
+ type = 'scatter', mode = 'markers') %>%
+ layout(shapes = list(vline(2.5), list(type = "rect",
+ fillcolor = "red", line = list(color = "red"), opacity = 0.2,
+ y0 = 0.9, y1 = 2.6, x0 = 0.5, x1 = 7.5)))
+fig
+```
+
+### Horizontal and Vertical Lines in Dash
+
+[Dash for R](https://dashr.plotly.com) is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
+
+Learn about how to install Dash for R at https://dashr.plot.ly/installation.
+
+Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument.
+
+```{r}
+
+library(dash)
+library(dashCoreComponents)
+library(dashHtmlComponents)
+library(plotly)
+data("iris")
+
+vline <- function(x = 0, color = "green") {
+ list(
+ type = "line",
+ y0 = 0,
+ y1 = 1,
+ yref = "paper",
+ x0 = x,
+ x1 = x,
+ line = list(color = color, dash="dot")
+ )
+}
+
+app <- Dash$new()
+
+app$layout(
+ htmlDiv(
+ list(
+ dccGraph(id = 'graph-with-slider'),
+ htmlLabel('Position of hline'),
+ dccSlider(
+ id='slider',
+ min = 1,
+ max = 7,
+ marks = c("","1","","","","","","7"),
+ value = 2.5,
+ step=0.1
+ )
+
+ )
+ )
+)
+app$callback(
+ output(id = 'graph-with-slider', property='figure'),
+ params=list(input(id='slider', property='value')),
+ function(value) {
+ fig <- plot_ly(data = iris, x = ~Petal.Length, y = ~Petal.Width,
+ type = 'scatter', mode = 'markers') %>%
+ layout(shapes = list(vline(value), list(type = "rect",
+ fillcolor = "red", line = list(color = "red"), opacity = 0.2,
+ y0 = 0.9, y1 = 2.6, x0 = 0.5, x1 = 7.5)))
+ return(fig)
+ })
+```
+
+After executing this code, give app$run_server() in the console to start the dash.
+
+### Adding Text Annotations
+
+[Text annotations](https://plotly.com/r/text-and-annotations/) can optionally be added to a shape using the `add_text` keyword argument, and positioned using the `x` and `y` arguments:
+
+```{r}
+library(tidyquant)
+library(plotly)
+tickers = c("GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT")
+for (i in tickers){
+getSymbols(i,
+ from = "2018-01-01",
+ to = "2019-12-31")}
+stock <- data.frame(GOOG$GOOG.Adjusted,
+ AAPL$AAPL.Adjusted,
+ AMZN$AMZN.Adjusted,
+ FB$FB.Adjusted,
+ NFLX$NFLX.Adjusted,
+ MSFT$MSFT.Adjusted)
+stock$GOOG.Adjusted <- stock$GOOG.Adjusted/stock$GOOG.Adjusted[1]
+stock$AAPL.Adjusted <- stock$AAPL.Adjusted/stock$AAPL.Adjusted[1]
+stock$AMZN.Adjusted <- stock$AMZN.Adjusted/stock$AMZN.Adjusted[1]
+stock$FB.Adjusted <- stock$FB.Adjusted/stock$FB.Adjusted[1]
+stock$NFLX.Adjusted <- stock$NFLX.Adjusted/stock$NFLX.Adjusted[1]
+stock$MSFT.Adjusted <- stock$MSFT.Adjusted/stock$MSFT.Adjusted[1]
+stock <- data.frame(stock,rownames(stock))
+colnames(stock) <- append(tickers,'Dates')
+
+hline <- function(y = 0, color = "black") {
+ list(
+ type = "line",
+ x0 = 0,
+ x1 = 1,
+ xref = "paper",
+ y0 = y,
+ y1 = y,
+ line = list(color = color, dash="dot")
+ )
+}
+
+x <- list(
+ title = "date"
+)
+y <- list(
+ title = "value"
+)
+
+fig <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
+ add_trace(x = ~Dates, y = ~GOOG, name = 'GOOG')%>%
+ add_trace(x = ~Dates, y = ~AAPL, name = 'AAPL')%>%
+ add_trace(x = ~Dates, y = ~AMZN, name = 'AMZN')%>%
+ add_trace(x = ~Dates, y = ~FB, name = 'FB')%>%
+ add_trace(x = ~Dates, y = ~NFLX, name = 'NFLX')%>%
+ add_trace(x = ~Dates, y = ~MSFT, name = 'MSFT')%>%
+ layout(legend=list(title=list(text='company')), shapes = list(list(type = "rect", text = 'Decline', fillcolor = "green", line = list(color = "green"),
+ opacity = 0.2, y0 = 0.6, y1 = 2.25, x0 = "2018-10-01", x1 = "2018-12-17"), hline(1)), xaxis = x, yaxis = y)%>%
+ add_text(showlegend = FALSE, x = c("2018-11-01","2019-09-20"), y = c(2.2,0.95),
+ text = c("decline","Jan 1, 2018 baseline"))
+options(warn = -1)
+fig
+```
+
+Extra formatting of the annotation can be done by adding `textfont` argument.
+
+```{r}
+library(tidyquant)
+library(plotly)
+tickers = c("GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT")
+for (i in tickers){
+ getSymbols(i,
+ from = "2018-01-01",
+ to = "2019-12-31")}
+stock <- data.frame(GOOG$GOOG.Adjusted,
+ AAPL$AAPL.Adjusted,
+ AMZN$AMZN.Adjusted,
+ FB$FB.Adjusted,
+ NFLX$NFLX.Adjusted,
+ MSFT$MSFT.Adjusted)
+stock$GOOG.Adjusted <- stock$GOOG.Adjusted/stock$GOOG.Adjusted[1]
+stock$AAPL.Adjusted <- stock$AAPL.Adjusted/stock$AAPL.Adjusted[1]
+stock$AMZN.Adjusted <- stock$AMZN.Adjusted/stock$AMZN.Adjusted[1]
+stock$FB.Adjusted <- stock$FB.Adjusted/stock$FB.Adjusted[1]
+stock$NFLX.Adjusted <- stock$NFLX.Adjusted/stock$NFLX.Adjusted[1]
+stock$MSFT.Adjusted <- stock$MSFT.Adjusted/stock$MSFT.Adjusted[1]
+stock <- data.frame(stock,rownames(stock))
+colnames(stock) <- append(tickers,'Dates')
+
+hline <- function(y = 0, color = "black") {
+ list(
+ type = "line",
+ x0 = 0,
+ x1 = 1,
+ xref = "paper",
+ y0 = y,
+ y1 = y,
+ line = list(color = color, dash="dot")
+ )
+}
+
+x <- list(
+ title = "date"
+)
+y <- list(
+ title = "value"
+)
+
+fig <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
+ add_trace(x = ~Dates, y = ~GOOG, name = 'GOOG')%>%
+ add_trace(x = ~Dates, y = ~AAPL, name = 'AAPL')%>%
+ add_trace(x = ~Dates, y = ~AMZN, name = 'AMZN')%>%
+ add_trace(x = ~Dates, y = ~FB, name = 'FB')%>%
+ add_trace(x = ~Dates, y = ~NFLX, name = 'NFLX')%>%
+ add_trace(x = ~Dates, y = ~MSFT, name = 'MSFT')%>%
+ layout(legend=list(title=list(text='company')), shapes = list(list(type = "rect", text = 'decline', fillcolor = "green", line = list(color = "green"),
+ opacity = 0.2, y0 = 0.6, y1 = 2.25, x0 = "2018-10-01", x1 = "2018-12-17"), hline(1)), xaxis = x, yaxis = y)%>%
+ add_text(showlegend = FALSE, x = c("2018-11-10","2019-08-20"), y = c(2.2,0.95),
+ text = c("decline","Jan 1, 2018 baseline"),
+ textfont = list(color = c('#000000','blue'), size = c(20,20), family = c("Open Sans","Times New Roman")))
+options(warn = -1)
+fig
+```
+
+### Adding to Multiple Facets / Subplots
+
+The same line or box is added to multiple plots, and these plots are finally added to the existing figure using `subplot` method.
+
+```{r}
+library(tidyquant)
+library(plotly)
+tickers = c("GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT")
+for (i in tickers){
+ getSymbols(i,
+ from = "2018-01-01",
+ to = "2019-12-31")}
+hline <- function(y = 0, color = "black") {
+ list(
+ type = "line",
+ x0 = 0,
+ x1 = 1,
+ xref = "paper",
+ y0 = y,
+ y1 = y,
+ line = list(color = color, dash="dot")
+ )
+}
+
+x <- list(
+ title = "date"
+)
+y <- list(
+ title = "value"
+)
+
+stock <- data.frame(GOOG$GOOG.Adjusted,
+ AAPL$AAPL.Adjusted,
+ AMZN$AMZN.Adjusted,
+ FB$FB.Adjusted,
+ NFLX$NFLX.Adjusted,
+ MSFT$MSFT.Adjusted)
+stock$GOOG.Adjusted <- stock$GOOG.Adjusted/stock$GOOG.Adjusted[1]
+stock$AAPL.Adjusted <- stock$AAPL.Adjusted/stock$AAPL.Adjusted[1]
+stock$AMZN.Adjusted <- stock$AMZN.Adjusted/stock$AMZN.Adjusted[1]
+stock$FB.Adjusted <- stock$FB.Adjusted/stock$FB.Adjusted[1]
+stock$NFLX.Adjusted <- stock$NFLX.Adjusted/stock$NFLX.Adjusted[1]
+stock$MSFT.Adjusted <- stock$MSFT.Adjusted/stock$MSFT.Adjusted[1]
+stock <- data.frame(stock,rownames(stock))
+colnames(stock) <- append(tickers,'Dates')
+
+ax <- list(
+ title = "",
+ zeroline = FALSE,
+ showline = FALSE,
+ showticklabels = FALSE
+)
+
+fig1 <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
+ add_trace(x = ~Dates, y = ~GOOG, name = 'GOOG')%>%
+ layout(legend=list(title=list(text='company')), xaxis = ax, yaxis = list(range = c(0.5,2), title = 'value'), shapes = list(list(type = "rect", text = 'Decline', fillcolor = "green", line = list(color = "green"),
+ opacity = 0.2, y0 = 0.6, y1 = 2, x0 = "2018-10-01", x1 = "2018-12-17"), hline(1)), xaxis = x, yaxis = y)%>%
+ add_text(showlegend = FALSE, x = c("2018-11-5","2019-10-20"), y = c(1.9,0.95),
+ text = c("decline","Jan 1, 2018 baseline"))
+
+fig2 <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
+ add_trace(x = ~Dates, y = ~AAPL, name = 'AAPL')%>%
+ layout(legend=list(title=list(text='company')), xaxis = ax, yaxis = list(range = c(0.5,2),title = '', showticklabels = FALSE), shapes = list( hline(1)), xaxis = x, yaxis = y)%>%
+ add_text(showlegend = FALSE, x = c("2019-10-20"), y = c(0.95),
+ text = c("Jan 1, 2018 baseline"))
+
+fig3 <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
+ add_trace(x = ~Dates, y = ~AMZN, name = 'AMZN')%>%
+ layout(legend=list(title=list(text='company')), xaxis = ax, yaxis = list(range = c(0.5,2), title = 'value'), shapes = list(type = "rect", text = 'Decline', fillcolor = "green", line = list(color = "green"),
+ opacity = 0.2, y0 = 0.6, y1 = 2, x0 = "2018-10-01", x1 = "2018-12-17"))%>%
+ add_text(showlegend = FALSE, x = c("2018-11-5"), y = c(1.9),
+ text = c("decline"))
+
+fig4 <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
+ add_trace(x = ~Dates, y = ~FB, name = 'FB')%>%
+ layout(legend=list(title=list(text='company')), xaxis = ax, yaxis = list(range = c(0.5,2),title = '', showticklabels = FALSE))
+
+fig5 <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
+ add_trace(x = ~Dates, y = ~NFLX, name = 'NFLX')%>%
+ layout(legend=list(title=list(text='company')), xaxis = list(title = 'Date'), yaxis = list(range = c(0.5,2), title = 'value'), shapes = list(type = "rect", text = 'Decline', fillcolor = "green", line = list(color = "green"),
+ opacity = 0.2, y0 = 0.6, y1 = 2, x0 = "2018-10-01", x1 = "2018-12-17"))%>%
+ add_text(showlegend = FALSE, x = c("2018-11-5"), y = c(1.9),
+ text = c("decline"))
+
+fig6 <- plot_ly(stock, type = 'scatter', mode = 'lines')%>%
+ add_trace(x = ~Dates, y = ~MSFT, name = 'MSFT')%>%
+ layout( legend=list(title=list(text='company')), yaxis = list(range = c(0.5,2) ,showticklabels = FALSE, title =''), xaxis = list(title = 'Date')
+ )
+
+fig <- subplot(fig1, fig2, fig3, fig4, fig5, fig6,
+ nrows = 3, titleY = TRUE, titleX = TRUE)
+annotations = list(
+ list(
+ x = 0.225,
+ y = 1.0,
+ font = list(size = 10),
+ text = "company=GOOG",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.775,
+ y = 1,
+ font = list(size = 10),
+ text = "company=AAPL",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.225,
+ y = 0.666,
+ font = list(size = 10),
+ text = "company=AMZN",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.775,
+ y = 0.666,
+ font = list(size = 10),
+ text = "company=FB",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.225,
+ y = 0.333,
+ font = list(size = 10),
+ text = "company=NFLX",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.775,
+ y = 0.333,
+ font = list(size = 10),
+ text = "company=MSFT",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ )
+)
+
+fig <- fig %>%layout(annotations = annotations)
+options(warn = -1)
+fig
+```
+### Reference
+
+More details are available about [layout shapes](https://plotly.com/r/shapes/) and [annotations](https://plotly.com/r/text-and-annotations/),
+[adding line](https://plotly.com/r/shapes/#lines),
+[adding rectangle](https://plotly.com/r/shapes/#rectangles).
\ No newline at end of file
diff --git a/r/2021-08-04-figure-labels.rmd b/r/2021-08-04-figure-labels.rmd
new file mode 100644
index 00000000..98a94eaa
--- /dev/null
+++ b/r/2021-08-04-figure-labels.rmd
@@ -0,0 +1,102 @@
+## Setting the Font, Title, Legend Entries, and Axis Titles in R
+
+How to set the global font, title, legend-entries, and axis-titles in R.
+
+### Automatic Labelling with Plotly
+
+When using Plotly, your axes is automatically labelled, and it's easy to override the automation for a customized figure using the `labels` keyword argument. The title of your figure is up to you though!
+
+Here's a figure with automatic labels and then the same figure with overridden labels. Note the fact that when overriding labels, the axes, legend title *and hover labels* reflect the specified labels automatically.
+
+```{r}
+
+library(plotly)
+
+data("iris")
+
+fig1 <- plot_ly(data = iris ,x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species, type = 'scatter', mode = 'markers')%>%
+ layout(title = 'Automatic Labels Based on Data Frame Column Names')
+fig1
+
+#Manually specifying labels
+
+fig2 <- plot_ly(data = iris ,x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species, type = 'scatter', mode = 'markers')%>%
+ layout(title = 'Manually Specified Labels', xaxis = list(title = 'Sepal Length (cm)'),
+ yaxis = list(title = 'Sepal Width (cm)'), legend = list(title=list(text=' Species of Iris ')))
+fig2
+```
+
+
+### Global and Local Font Specification
+
+You can set the figure-wide font with the `layout.font.family` attribute, which will apply to all titles and tick labels, but this can be overridden for specific plot items like individual axes and legend titles etc. In the following figure, we set the figure-wide font to Courier New in blue, and then override this for certain parts of the figure.
+
+```{r}
+library(plotly)
+data(iris)
+
+t <- list(
+ family = "Courier New",
+ size = 14,
+ color = "blue")
+t1 <- list(
+ family = "Times New Roman",
+ color = "red"
+)
+t2 <- list(
+ family = "Courier New",
+ size = 14,
+ color = "green")
+t3 <- list(family = 'Arial')
+
+fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species,
+ type = 'scatter', mode = 'markers')%>%
+ layout(title= list(text = "Playing with Fonts",font = t1), font=t,
+ legend=list(title=list(text='Species',font = t2)),
+ xaxis = list(title = list(text ='Sepal.Length', font = t3)))
+fig
+```
+
+### Manual Labelling in Plotly
+
+Explicitly Labeling traces and axes in Plotly.
+
+```{r}
+
+library(plotly)
+t <- list(
+ family = "Courier New, monospace",
+ size = 15,
+ color = "RebeccaPurple")
+x1 = c(0, 1, 2, 3, 4, 5, 6, 7, 8)
+y1 = c(0, 1, 2, 3, 4, 5, 6, 7, 8)
+
+x2 = c(0, 1, 2, 3, 4, 5, 6, 7, 8)
+y2 = c(1, 0, 3, 2, 5, 4, 7, 6, 8)
+
+df = data.frame(x1, y1, x2, y2)
+
+fig <- plot_ly()%>%
+ add_trace(df, x = ~x1, y = ~y1, type = 'scatter', mode = 'lines+markers', name = 'Name of Trace 1')%>%
+ add_trace(df, x = ~x2, y = ~y2, type = 'scatter', mode = 'lines+markers', name = 'Name of Trace 2')%>%
+ layout(title = 'Plot Title', xaxis = list(title = 'X Axis Title'), font=t,
+ yaxis = list(title = 'Y Axis Title'), legend = list(title=list(text='Legend Title')))
+
+fig
+```
+
+The configuration of the legend is discussed in detail in the [Legends](https://plotly.com/r/legend/) page.
+
+### Align Plot Title
+The following example shows how to align the plot title in [layout.title](https://plotly.com/r/reference/layout/#layout-title). `x` sets the x position with respect to `xref` from "0" (left) to "1" (right), and `y` sets the y position with respect to `yref` from "0" (bottom) to "1" (top). Moreover, you can define `xanchor` to `left`,`right`, or `center` for setting the title's horizontal alignment with respect to its x position, and/or `yanchor` to `top`, `bottom`, or `middle` for setting the title's vertical alignment with respect to its y position.
+
+```{r}
+library(plotly)
+
+fig <- plot_ly(x= c('Mon', 'Tue', 'Wed'), y= c(3,1,4), type= 'scatter', mode= 'lines+markers')%>%
+ layout(title = list(text='Plot Title', y = 0.95, x = 0.5, xanchor = 'center', yanchor = 'top'))
+fig
+```
+
+#### Reference
+See https://plotly.com/r/reference/layout/ for more information!
diff --git a/r/2021-08-06-images.rmd b/r/2021-08-06-images.rmd
new file mode 100644
index 00000000..36a18da0
--- /dev/null
+++ b/r/2021-08-06-images.rmd
@@ -0,0 +1,361 @@
+## Images in R
+How to add images to charts as background images or logos.
+
+### Add a Background Image
+
+In this page we explain how to add static, non-interactive images as background, logo or annotation images to a figure. For exploring image data in interactive charts, see the [tutorial on displaying image data](https://plotly.com/r/displaying-images/).
+
+A background image can be added to the layout of a figure by setting the `images` parameter of `plot_ly.layout`. The
+`source` attribute of a `layout.images` can be the URL of an image, or a PIL
+Image object (`from PIL import Image; img = Image.open('filename.png')`).
+
+```{r}
+library('plotly')
+# Create figure
+plot_ly(x = c(0, 0.5, 1, 2, 2.2), y = c(1.23, 2.5, 0.42, 3, 1), type = 'scatter', mode = 'lines+markers') %>%
+ # Add trace
+ layout(
+ images = list(
+ list(
+ # Add images
+ source = "https://images.plot.ly/language-icons/api-home/r-logo.png?raw=true",
+ xref = "x",
+ yref = "y",
+ x = 0.2,
+ y = 3,
+ sizex = 2,
+ sizey = 2,
+ sizing = "stretch",
+ opacity = 0.4,
+ layer = "below"
+ )
+ )
+ )
+```
+
+### Add a Logo
+See more examples of [adding logos to charts](https://plotly.com/r/logos/)!
+
+```{r}
+library(plotly)
+x= c("-35.3", "-15.9", "-15.8", "-15.6", "-11.1",
+ "-9.6", "-9.2", "-3.5", "-1.9", "-0.9",
+ "1.0", "1.4", "1.7", "2.0", "2.8", "6.2",
+ "8.1", "8.5", "8.5", "8.6", "11.4", "12.5",
+ "13.3", "13.7", "14.4", "17.5", "17.7",
+ "18.9", "25.1", "28.9", "41.4")
+
+y = c("Designers, musicians, artists, etc.",
+ "Secretaries and administrative assistants",
+ "Waiters and servers", "Archivists, curators, and librarians",
+ "Sales and related", "Childcare workers, home car workers, etc.",
+ "Food preparation occupations", "Janitors, maids, etc.",
+ "Healthcare technicians, assistants. and aides",
+ "Counselors, social and religious workers",
+ "Physical, life and social scientists", "Construction",
+ "Factory assembly workers", "Machinists, repairmen, etc.",
+ "Media and communications workers", "Teachers",
+ "Mechanics, repairmen, etc.", "Financial analysts and advisers",
+ "Farming, fishing and forestry workers",
+ "Truck drivers, heavy equipment operator, etc.", "Accountants and auditors",
+ "Human resources, management analysts, etc.", "Managers",
+ "Lawyers and judges", "Engineers, architects and surveyors",
+ "Nurses", "Legal support workers",
+ "Computer programmers and system admin.", "Police officers and firefighters",
+ "Chief executives", "Doctors, dentists and surgeons")
+
+df = data.frame(x,y,stringsAsFactors = FALSE)
+
+m = list(r=20, l=300, b=75, t=125)
+
+fig <- plot_ly(data = df, x = ~x, y = ~y, type = 'bar', orientation = 'h',
+ marker = list(color = 'rgb(253, 240, 54)',
+ line = list(width = 2, color = 'rgb(0, 0, 0)'))) %>%
+ layout( xaxis = list(title = ""), yaxis = list(title = ""),
+ images = list(
+ list(
+ source = "https://raw.githubusercontent.com/cldougl/plot_images/add_r_img/vox.png",
+ xref = "paper",
+ yref = "paper",
+ x = 1.05,
+ y = 1.05,
+ sizex = 0.2,
+ sizey = 0.2,
+ xanchor="right",
+ yanchor="bottom"
+ )
+ ) )
+
+fig <- fig %>% layout(autosize = F, margin = m,
+ title=(paste("Moving Up, Moving Down
" ,
+ "Percentile change in income between childhood and adulthood")),
+ hovermode="x"
+ )
+fig
+```
+
+### Zoom on Static Images
+
+```{r}
+library(plotly)
+
+#Constants
+img_width = 1600
+img_height = 900
+scale_factor = 0.5
+
+
+# Add invisible scatter trace.
+# This trace is added to help the autoresize logic work.
+fig <- plot_ly(width=img_width * scale_factor,
+ height=img_height * scale_factor
+) %>%
+ add_trace( x= c(0, img_width * scale_factor),
+ y= c(0, img_height * scale_factor),
+ type = 'scatter', mode = 'markers', alpha = 0)
+
+# Configure axes
+xconfig <- list(
+ title = "",
+ zeroline = FALSE,
+ showline = FALSE,
+ showticklabels = FALSE,
+ showgrid = FALSE,
+ range = c(0, img_width * scale_factor)
+)
+
+yconfig <- list(
+ title = "",
+ zeroline = FALSE,
+ showline = FALSE,
+ showticklabels = FALSE,
+ showgrid = FALSE,
+ range = c(0, img_height * scale_factor),
+ scaleanchor="x"
+)
+
+fig <- fig %>% layout(xaxis = xconfig, yaxis = yconfig)
+
+# Add image
+
+fig <- fig %>% layout(
+ images = list(
+ list(
+ source = "https://raw.githubusercontent.com/michaelbabyn/plot_data/master/bridge.jpg",
+ x=0,
+ sizex=img_width * scale_factor,
+ y=img_height * scale_factor,
+ sizey=img_height * scale_factor,
+ xref="x",
+ yref="y",
+ opacity=1.0,
+ layer="below",
+ sizing="stretch"
+ )
+ ))
+
+# Configure other layout
+
+m = list(r=0, l=0, b=0, t=0)
+fig <- fig %>% layout(margin = m)
+fig
+```
+
+### Annotating layout image with shapes
+It can be useful to add shapes to a layout image, for highlighting an object, drawing bounding boxes as part of a machine learning training set, or identifying seeds for a segmentation algorithm.
+
+In order to enable shape drawing, you need to
+
++ define a dragmode corresponding to a drawing tool (`'drawline'`,`'drawopenpath'`, `'drawclosedpath'`, `'drawcircle'`, or `'drawrect'`)
+
++ add [modebar buttons](https://plotly-r.com/control-modebar.html) corresponding to the drawing tools you wish to use.
+
+The style of new shapes is specified by the `newshape` layout attribute. Shapes can be selected and modified after they have been drawn. More details and examples are given in the [tutorial on shapes](https://plotly.com/r/shapes/#drawing-shapes-on-cartesian-plots).
+
+Drawing or modifying a shape triggers a `relayout` event, which [can be captured by a callback inside a Dash application](https://dashr.plotly.com/interactive-graphing).
+
+```{r}
+library(plotly)
+
+#Constants
+img_width = 1600
+img_height = 900
+scale_factor = 0.5
+
+fig <- plot_ly() %>%
+ add_trace( x= c(0, img_width ),
+ y= c(0, img_height ),
+ type = 'scatter', mode = 'markers', alpha = 0)%>%
+ layout(images = list(
+ list(
+ source = "https://raw.githubusercontent.com/michaelbabyn/plot_data/master/bridge.jpg",
+ x=0,
+ sizex=img_width,
+ y=0,
+ sizey=img_height,
+ xref="x",
+ yref="y",
+ opacity=1.0,
+ layer="below"
+ )
+ ))
+
+xconfig <- list(
+ title = "",
+ showgrid = FALSE,
+ range = c(0, img_width)
+)
+
+yconfig <- list(
+ title = "",
+ showgrid = FALSE,
+ range = c(img_height,0),
+ scaleanchor="x"
+)
+
+fig <- fig %>% layout(xaxis = xconfig, yaxis = yconfig)
+
+#Add lineshape
+fig <- fig %>%
+ add_segments(x = 650, xend = 1080, y = 380, yend = 180, line = list( color = 'cyan'),inherit = FALSE, showlegend = FALSE)
+
+fig <- fig %>% layout(dragmode='drawrect',
+ newshape=list(line = list(color='cyan')),
+ title = 'Drag to add annotations - use modebar to change drawing tool')
+
+#Add modebar buttons
+fig <- fig %>%
+ config(modeBarButtonsToAdd = c('drawline',
+ 'drawopenpath',
+ 'drawclosedpath',
+ 'drawcircle',
+ 'drawrect',
+ 'eraseshape'))
+
+fig
+```
+
+
+### Images Placed Relative to Axes
+
+Using `xref='x domain'` or `yref='y domain'`, images can be placed relative to
+axes. As an example, the following shows how to put an image in the top corner
+of a subplot (try panning and zooming the resulting figure):
+
+```{r}
+library(plotly)
+
+db1 <- iris[iris$Species == "setosa", ]
+db2 <- iris[iris$Species == "versicolor", ]
+db3 <- iris[iris$Species == "virginica", ]
+
+fig1 <- plot_ly(data = db1, x = ~Sepal.Length, y = ~Sepal.Width, type = 'scatter', mode = 'markers') %>%
+ layout(xaxis = list(range = c(4,8)))
+# add images
+fig1 <- fig1 %>% layout(
+ images = list(
+ list(
+ # sources of images
+ source = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fe/Iris_setosa_var._setosa_%282595031014%29.jpg/360px-Iris_setosa_var._setosa_%282595031014%29.jpg",
+ row=1,
+ col=1,
+ source=1,
+ xref="x domain",
+ yref="y domain",
+ x=1,
+ y=1,
+ xanchor="right",
+ yanchor="top",
+ sizex=0.2,
+ sizey=0.2
+ )
+ ))
+
+fig2 <- plot_ly(data = db2, x = ~Sepal.Length, y = ~Sepal.Width, type = 'scatter', mode = 'markers') %>%
+ layout(xaxis = list(range = c(4,8)))
+# add images
+fig2 <- fig2 %>% layout(
+ images = list(
+ list(
+ # sources of images
+ source = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Iris_versicolor_quebec_1.jpg/320px-Iris_versicolor_quebec_1.jpg",
+ row=1,
+ col=2,
+ source=2,
+ xref="x domain",
+ yref="y domain",
+ x=2.05,
+ y=1,
+ xanchor="right",
+ yanchor="top",
+ sizex=0.2,
+ sizey=0.2
+ )
+ ))
+
+fig3 <- plot_ly(data = db3, x = ~Sepal.Length, y = ~Sepal.Width, type = 'scatter', mode = 'markers') %>%
+ layout(xaxis = list(range = c(4,8), title = 'Sepal..Length'))
+# add images
+fig3 <- fig3 %>% layout(
+ images = list(
+ list(
+ # sources of images
+ source = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Iris_virginica_2.jpg/480px-Iris_virginica_2.jpg",
+ row=1,
+ col=3,
+ source=2,
+ xref="x domain",
+ yref="y domain",
+ x=3.15,
+ y=1,
+ xanchor="right",
+ yanchor="top",
+ sizex=0.2,
+ sizey=0.2
+ )
+ ))
+
+fig <- subplot(fig1, fig2, fig3, shareY = TRUE, shareX = TRUE) %>% layout(showlegend = FALSE)
+
+annotations = list(
+ list(
+ x = 0.2,
+ y = 1.0,
+ font = list(size = 10),
+ text = "species=setosa",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.8,
+ y = 1,
+ font = list(size = 10),
+ text = "species=versicolor",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.5,
+ y = 1,
+ font = list(size = 10),
+ text = "species=virginica",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ))
+
+fig <- fig %>%layout(annotations = annotations)
+options(warn = -1)
+fig
+```
+
+#### Reference
+See https://plotly.com/r/reference/layout/images/ for more information and chart attribute options!
\ No newline at end of file
diff --git a/r/2021-08-09-subplots.rmd b/r/2021-08-09-subplots.rmd
new file mode 100644
index 00000000..e2a2b186
--- /dev/null
+++ b/r/2021-08-09-subplots.rmd
@@ -0,0 +1,477 @@
+---
+title: "Subplots in R"
+---
+
+How to make subplots in with Plotly's R graphing library. Examples of stacked, custom-sized, gridded, and annotated subplots.
+
+### Subplots and Plotly Express
+
+Plotly’s R graphing library makes it easy to create interactive, publication-quality graphs.
+
+Plotly also has subplot capabilities.
+
+This page documents the usage of the lower-level `subplot` module.
+
+#### Simple Subplot
+
+Figures with subplots are created using the `subplot` function.
+
+Here is an example of creating a figure that includes two `scatter` traces which are side-by-side since there are 2 columns and 1 row in the subplot layout.
+
+```{r}
+
+library(plotly)
+
+fig1 <- plot_ly(x = c(1,2,3), y = c(4,5,6), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+
+fig2 <- plot_ly(x = c(20,30,40), y = c(50,60,70), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+fig <- subplot(fig1, fig2) %>%
+ layout(title = 'Side By Side Subplots')
+fig
+
+```
+
+#### Stacked Subplots
+
+Here is an example of creating a figure with subplots that are stacked on top of each other since there are 3 rows and 1 column in the subplot layout.
+
+```{r}
+library(plotly)
+fig1 <- plot_ly(x = c(3, 4, 5), y = c(1000, 1100, 1200), type = 'scatter', mode = 'lines+markers')
+fig2 <- plot_ly(x = c(2, 3, 4), y = c(100, 110, 120), type = 'scatter', mode = 'lines+markers')
+fig3 <- plot_ly(x = c(0, 1, 2), y = c(10, 11, 12), type = 'scatter', mode = 'lines+markers')
+fig <- subplot(fig1, fig2, fig3, nrows = 3) %>%
+ layout(title = list(text = "Stacked Subplots"))
+fig
+
+```
+
+#### Multiple Subplots
+
+Here is an example of creating a 2 x 2 subplot grid and populating each subplot with `scatter` trace.
+
+```{r}
+
+library(plotly)
+
+fig1 <- plot_ly(x = c(1,2,3), y = c(4,5,6), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+
+fig2 <- plot_ly(x = c(20,30,40), y = c(50,60,70), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+
+fig3 <- plot_ly(x = c(300,400,500), y = c(600,700,800), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+
+fig4 <- plot_ly(x = c(4000,5000,6000), y = c(7000,8000,9000), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+fig <- subplot(fig1, fig2, fig3, fig4, nrows = 2)
+fig
+```
+
+#### Multiple Subplots with Titles
+The `annotations` argument can be used to position text annotations as titles for each subplot.
+
+Here is an example of adding subplot titles to a 2 x 2 subplot grid of scatter traces.
+
+```{r}
+
+library(plotly)
+
+fig1 <- plot_ly(x = c(1,2,3), y = c(4,5,6), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+
+fig2 <- plot_ly(x = c(20,30,40), y = c(50,60,70), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+
+fig3 <- plot_ly(x = c(300,400,500), y = c(600,700,800), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+
+fig4 <- plot_ly(x = c(4000,5000,6000), y = c(7000,8000,9000), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+fig <- subplot(fig1, fig2, fig3, fig4, nrows = 2)%>%
+ layout(title = 'Multiple Subplots with Titles')
+
+annotations = list(
+ list(
+ x = 0.2,
+ y = 1.0,
+ text = "Plot 1",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.8,
+ y = 1,
+ text = "Plot 2",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.2,
+ y = 0.45,
+ text = "Plot 3",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.8,
+ y = 0.45,
+ text = "Plot 4",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ))
+
+fig <- fig %>%layout(annotations = annotations)
+#options(warn = -1)
+fig
+```
+
+#### Subplots with Annotations
+
+```{r}
+library(plotly)
+fig1 <- plot_ly(x = c(1, 2, 3), y = c(4, 5, 6), type = 'scatter', mode = 'markers+text'
+ ,text = list("Text D", "Text E", "Text F"), textposition = "bottom center"
+ ,texttemplate = "%{text}")
+
+fig2 <- plot_ly(x = c(20, 30, 40), y = c(50, 60, 70), type = 'scatter', mode = 'markers+text'
+ ,text = list("Text D", "Text E", "Text F"), textposition = "bottom center"
+ ,texttemplate = "%{text}")
+
+fig <- subplot(fig1, fig2)%>%
+ layout(title = list(text = "Subplots with Annotations"))
+fig
+
+```
+
+#### Customize Subplot Column Widths and Row Heights
+The `widths` argument can be used to customize the relative widths of the columns in a subplot grid. It should be set in a list of numbers so that they sum to 1, and used to compute the relative widths of the subplot grid columns. The `heights` argument serves the same purpose for controlling the relative heights of rows in the subplot grid.
+
+Here is an example of creating a figure with two scatter traces in side-by-side subplots. The left subplot is set to be wider than the right one.
+
+```{r}
+
+library(plotly)
+
+fig1 <- plot_ly(x = c(1,2,3), y = c(4,5,6), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+
+fig2 <- plot_ly(x = c(20,30,40), y = c(50,60,70), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))
+
+fig <- subplot(fig1, fig2, widths = c(0.7, 0.3))
+fig
+```
+
+#### Subplots in Dash
+
+[Dash for R](https://dashr.plotly.com) is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
+
+Learn about how to install Dash for R at https://dashr.plot.ly/installation.
+
+Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument.
+
+
+```{r}
+
+library(dash)
+library(dashCoreComponents)
+library(dashHtmlComponents)
+library(plotly)
+
+app <- Dash$new()
+
+app$layout(
+ htmlDiv(
+ list(
+ dccGraph(id = 'graph-with-slider'),
+ htmlLabel('Subplots Width:'),
+ dccSlider(
+ id='slider',
+ min = 0,
+ max = 1,
+ value = 0.5,
+ step=0.01
+ )
+
+ )
+ )
+)
+app$callback(
+ output(id = 'graph-with-slider', property='figure'),
+ params=list(input(id='slider', property='value')),
+ function(value) {
+ fig1 <- plot_ly(x = c(1,2,3), y = c(4,5,6), type = 'scatter', mode = 'lines+marker',
+ marker = list(line = list(width = 3)))
+
+
+ fig2 <- plot_ly(x = c(20,30,40), y = c(50,60,70), type = 'scatter', mode = 'lines+marker',
+ marker = list(line = list(width = 3)))
+
+ fig <- subplot(fig1, fig2, widths = c(value, 1 - value))
+ return(fig)
+ })
+```
+
+After executing this code, give app$run_server() in the console to start the dash.
+
+#### Customizing Subplot Axes
+After a figure with subplots is created using the `subplot` function, its axis properties (title, font, range, grid style, etc.) can be customized using the `xaxis` and `yaxis` graph object figure methods. By default, these methods apply to all of the x axes or y axes in the figure. The `row` and `col` arguments can be used to control which axes are targeted by the update.
+
+Here is an example that creates a figure with a 2 x 2 subplot grid, populates each subplot with a scatter trace, and then updates the x and y axis titles for each subplot individually.
+
+```{r}
+
+library(plotly)
+
+#Initialize figures
+fig1 <- plot_ly(x = c(1,2,3), y = c(4,5,6), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))%>%
+ layout(xaxis = list(title = 'xaxis1 title'), yaxis = list(title = 'yaxis1 title'))
+
+fig2 <- plot_ly(x = c(20,30,40), y = c(50,60,70), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))%>%
+ layout(xaxis = list(title = 'xaxis2 title', range = c(10,50)), yaxis = list(title = 'yaxis2 title', range = c(40,80)))
+
+
+fig3 <- plot_ly(x = c(300,400,500), y = c(600,700,800), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))%>%
+ layout(xaxis = list(title = 'xaxis3 title', showgrid = FALSE), yaxis = list(title = 'yaxis3 title', showgrid = FALSE))
+
+
+fig4 <- plot_ly(x = c(4000,5000,6000), y = c(7000,8000,9000), type = 'scatter', mode = 'lines+markers',
+ marker = list(line = list(width = 3)))%>%
+ layout(xaxis = list(title = 'xaxis4 title', type = 'log'), yaxis = list(title = 'yaxis4 title'))
+
+#creating subplot
+fig <- subplot(fig1, fig2, fig3, fig4, nrows = 2, titleY = TRUE, titleX = TRUE, margin = 0.1 )
+fig <- fig %>%layout(title = 'Customizing Subplot Axes')
+
+# Update title
+annotations = list(
+ list(
+ x = 0.2,
+ y = 1.0,
+ text = "Plot 1",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.8,
+ y = 1,
+ text = "Plot 2",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.2,
+ y = 0.4,
+ text = "Plot 3",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.8,
+ y = 0.4,
+ text = "Plot 4",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ))
+
+fig <- fig %>%layout(annotations = annotations)
+fig
+```
+
+#### Subplots with Shared X-Axes
+The `shareX_x` argument can be used to link the x axes of subplots in the resulting figure. The `margin` argument is used to control the vertical spacing between rows in the subplot grid.
+
+Here is an example that creates a figure with 3 vertically stacked subplots with linked x axes. A small margin value is used to reduce the spacing between subplot rows.
+
+```{r}
+
+library(plotly)
+fig1 <- plot_ly(x = c(3, 4, 5), y = c(1000, 1100, 1200), type = 'scatter', mode = 'lines+markers')
+fig2 <- plot_ly(x = c(2, 3, 4), y = c(100, 110, 120), type = 'scatter', mode = 'lines+markers')
+fig3 <- plot_ly(x = c(0, 1, 2), y = c(10, 11, 12), type = 'scatter', mode = 'lines+markers')
+fig <- subplot(fig1, fig2, fig3, nrows = 3, shareX = TRUE) %>%
+ layout(title = list(text = "Stacked Subplots with Shared X-Axes"))
+fig
+```
+
+#### Subplots with Shared Y-Axes
+The `shareY` argument can be used to link the y axes of subplots in the resulting figure.
+
+Here is an example that creates a figure with a 2 x 2 subplot grid, where the y axes of each row are linked.
+
+
+```{r}
+library(plotly)
+fig1 <- plot_ly(x = c(1, 2, 3), y = c(2, 3, 4), type = 'scatter', mode = 'lines+markers')
+fig2 <- plot_ly(x = c(20, 30, 40), y = c(5, 5, 5), type = 'scatter', mode = 'lines+markers')
+fig3 <- plot_ly(x = c(2, 3, 4), y = c(600, 700, 800), type = 'scatter', mode = 'lines+markers')
+fig4 <- plot_ly(x = c(4000, 5000, 6000), y = c(7000, 8000, 9000), type = 'scatter', mode = 'lines+markers')
+fig <- subplot(fig1, fig2, fig3, fig4, nrows = 2, shareY = TRUE) %>%
+ layout(title = list(text = "Multiple Subplots with Shared Y-Axes"))
+fig
+
+```
+
+### Subplots with Shared Colorscale
+
+To share colorscale information in multiple subplots, you can use [coloraxis](https://plotly.com/r/reference/layout/coloraxis/).
+
+```{r}
+
+library(plotly)
+
+fig1 <- plot_ly(x = c(1,2,3), y = c(4,5,6), type = 'bar',
+ marker = list(color = c(4,5,6), coloraxis="coloraxis"))
+
+fig2 <- plot_ly(x = c(1,2,3), y = c(2,3,5), type = 'bar',
+ marker = list(color = c(2,3,5), coloraxis="coloraxis"))
+
+fig <- subplot(fig1, fig2, shareY = TRUE)
+fig <- fig %>%layout(showlegend = FALSE, coloraxis=list(colorscale='RdBu'))
+fig
+```
+
+#### Custom Sized Subplot with Subplot Titles
+The heights and weights argument in subplot function is used to customly size the individual plots in the subplot.
+
+Here is an example that creates a 2 by 2 subplot grid containing 3 subplots.
+
+```{r}
+
+library(plotly)
+fig1 <- plot_ly(x = c(1, 2), y = c(1, 2), type = 'scatter', mode = 'lines+markers')
+fig2 <- plot_ly(x = c(1, 2), y = c(1, 2), type = 'scatter', mode = 'lines+markers')
+fig3 <- plot_ly(x = c(1, 2, 3), y = c(2, 1, 2), type = 'scatter', mode = 'lines+markers')%>%
+ layout(annotations = list(
+ list(x = 0.52 , y = 1.05, text = "Third Subplot", showarrow = F, xref='paper', yref='paper'))
+ )
+
+s1 <- subplot(fig1, fig2)%>%
+ layout(annotations = list(
+ list(x = 0.15 , y = 1.05, text = "First Subplot", showarrow = F, xref='paper', yref='paper'),
+ list(x = 0.85 , y = 1.05, text = "Second Subplot", showarrow = F, xref='paper', yref='paper'))
+)
+fig <- subplot(s1, fig3, nrows = 2, margin = 0.07) %>%
+ layout(title = "Specs with Subplot Title",
+ showlegend=FALSE,showlegend2=FALSE)
+
+fig
+```
+
+#### Multiple Custom Sized Subplots
+
+Here is an example that uses the `heights` and `weights` subplot options to create a custom subplot layout with subplots of mixed sizes.
+
+```{r}
+
+library(plotly)
+
+fig1 <- plot_ly(x = c(1,2), y = c(1,2), type = 'scatter', mode = 'lines+markers', name = '(1,1)',
+ marker = list(line = list(width = 3)))
+
+fig2 <- plot_ly(x = c(1,2), y = c(1,2), type = 'scatter', mode = 'lines+markers', name = '(2,1)',
+ marker = list(line = list(width = 3)))
+
+fig3 <- plot_ly(x = c(1,2), y = c(1,2), type = 'scatter', mode = 'lines+markers', name = '(1,2)',
+ marker = list(line = list(width = 3)))
+
+fig4 <- plot_ly(x = c(1,2), y = c(1,2), type = 'scatter', mode = 'lines+markers', name = '(3,1)',
+ marker = list(line = list(width = 3)))
+
+fig5 <- plot_ly(x = c(1,2), y = c(1,2), type = 'scatter', mode = 'lines+markers', name = '(5,1)',
+ marker = list(line = list(width = 3)))
+
+fig6 <- plot_ly(x = c(1,2), y = c(1,2), type = 'scatter', mode = 'lines+markers', name = '(5,2)',
+ marker = list(line = list(width = 3)))
+
+s1 <- subplot(fig1, fig2, nrows = 2)
+s2 <- subplot(s1, fig3)
+s3 <- subplot(s2, fig4, nrows = 2)
+s4 <- subplot(fig5, fig6)
+s5 <- subplot(s3, s4, nrows = 2, heights = c(0.8,0.2))
+s5
+```
+
+#### Subplots Types
+By default, the `subplots` function assumes that the traces that will be added to all subplots are 2-dimensional cartesian traces (e.g. `scatter`, `bar`, `histogram`, `violin`, etc.).
+
+
+ - trace type: A trace type name (e.g. `"bar"`, `"contour"`, `"density"`, `"scatter"`, etc.) which will be used to determine the appropriate subplot type for that trace.
+
+Here is an example that creates and populates a 2 x 2 subplot grid containing 4 different subplot types.
+
+```{r}
+library(plotly)
+
+fig1 <- plot_ly(y = c(2, 3, 1), type = 'bar')
+
+data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
+fig2 <- plot_ly(data, x = ~Women, y = ~Men, text = ~School, type = 'scatter', mode = 'markers', color = ~Gap, colors = 'Reds',
+ marker = list(size = ~Gap, opacity = 0.5))%>%
+ layout(xaxis = list(showgrid = FALSE),
+ yaxis = list(showgrid = FALSE))
+fig2 <- hide_colorbar(fig2)
+
+fig3<- plot_ly(z = ~volcano, type = "contour")
+fig3 <- hide_colorbar(fig3)
+
+density <- density(diamonds$carat)
+fig4 <- plot_ly(x = ~density$x, y = ~density$y, type = 'scatter', mode = 'lines', fill = 'tozeroy')
+fig4 <- fig4 %>% layout(xaxis = list(title = 'Carat'),
+ yaxis = list(title = 'Density'), showlegend=FALSE)
+
+fig <- subplot(fig1, fig2, fig3, fig4, nrows = 2, margin = 0.05)
+
+fig
+```
+
+
+#### Reference
+All of the axis properties are found here: https://plotly.com/r/axes/#
+
+
+```{r}
+help(subplot)
+```
diff --git a/r/2021-08-11-multiple-axes.rmd b/r/2021-08-11-multiple-axes.rmd
new file mode 100644
index 00000000..23b9c15b
--- /dev/null
+++ b/r/2021-08-11-multiple-axes.rmd
@@ -0,0 +1,196 @@
+# Multiple Axes in R
+How to make a graph with multiple axes (dual y-axis plots, plots with secondary axes) in R.
+
+
+### Multiple Y Axes and Plotly
+
+> *Note*: At this time, Plotly does not support multiple Y axes on a single figure. To make such a figure, use the [`subplot()`](https://plotly.com/r/subplot-charts/) function as documented below.
+
+
+## Two Y Axes
+
+```{r}
+library(plotly)
+
+fig <- plot_ly()
+# Add traces
+fig <- fig %>% add_trace(x = ~1:3, y = ~10*(4:6), name = "yaxis data", mode = "lines+markers", type = "scatter")
+
+ay <- list(
+ tickfont = list(color = "red"),
+ overlaying = "y",
+ side = "right",
+ title = "secondary yaxis title")
+
+fig <- fig %>% add_trace(x = ~2:4, y = ~4:6, name = "yaxis 2 data", yaxis = "y2", mode = "lines+markers", type = "scatter")
+
+# Set figure title, x and y-axes titles
+fig <- fig %>% layout(
+ title = "Double Y Axis Example", yaxis2 = ay,
+ xaxis = list(title="xaxis title "),
+ yaxis = list(title="primary yaxis title")
+)
+
+fig
+```
+
+## Multiple axes in Dash
+
+[Dash for R](https://dashr.plotly.com) is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
+
+Learn about how to install Dash for R at https://dashr.plot.ly/installation.
+
+Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument.
+
+```{r}
+library(dash)
+library(dashCoreComponents)
+library(dashHtmlComponents)
+library(plotly)
+
+app <- Dash$new()
+
+app$layout(
+ htmlDiv(
+ list(
+ dccGraph(id = 'graph'),
+ htmlLabel("Red line's axis:"),
+ dccRadioItems(
+ id='radio',
+ options = list(list(label = "Primary", value = "Primary"),
+ list(label = "Secondary", value = "Secondary")),
+ value = 'Secondary'
+ )
+ )
+ )
+)
+app$callback(
+ output(id = 'graph', property='figure'),
+ params=list(input(id='radio', property='value')),
+ function(value) {
+ if(value == 'Primary'){
+ fig <- plot_ly()
+ fig <- fig %>% add_trace(x = ~1:3, y = ~10*(4:6), name = "yaxis data", mode = "lines+markers", type = "scatter")
+ fig <- fig %>% add_trace(x = ~2:4, y = ~4:6, name = "yaxis 2 data", mode = "lines+markers", type = "scatter")
+ fig <- fig %>% layout(
+ title = "Double Y Axis Example",
+ xaxis = list(title="xaxis title"),
+ yaxis = list(title="primary yaxis title")
+ )
+ return(fig)
+ }
+ else{
+ fig <- plot_ly()
+ fig <- fig %>% add_trace(x = ~1:3, y = ~10*(4:6), name = "yaxis data", mode = "lines+markers", type = "scatter")
+
+ ay <- list(
+ overlaying = "y",
+ side = "right",
+ title = "secondary yaxis title")
+
+ fig <- fig %>% add_trace(x = ~2:4, y = ~4:6, name = "yaxis 2 data", yaxis = "y2", mode = "lines+markers", type = "scatter")
+
+ fig <- fig %>% layout(
+ title = "Double Y Axis Example", yaxis2 = ay,
+ xaxis = list(title="xaxis title"),
+ yaxis = list(title="primary yaxis title")
+ )
+ return(fig)
+ }
+ })
+#app$run_server()
+```
+
+Use `app$run_server()` to run the dash file.
+
+## Multiple Y-Axes Subplots
+
+```{r}
+library(plotly)
+# Top left
+p1 <- plot_ly() %>% add_trace(x = c(1, 2, 3), y = c(2, 52, 62),type="scatter",mode="lines+markers",yaxis="y", name="yaxis data") %>%
+ add_trace(x = c(1, 2, 3), y = c(40, 50, 60),type="scatter",mode="lines+markers",yaxis="y2", name="yaxis2 data") %>%
+ layout(yaxis=list(side="left"),
+ yaxis2=list(side="right",overlaying="y"),
+ showlegend=TRUE)
+# Top right
+p2 <-plot_ly() %>% add_trace(x = c(1, 2, 3), y = c(2, 52, 62),type="scatter",mode="lines+markers",yaxis="y", name="yaxis3 data") %>%
+ add_trace(x = c(1, 2, 3), y = c(40, 50, 60),type="scatter",mode="lines+markers",yaxis="y2", name="yaxis4 data") %>%
+ layout(yaxis=list(side="left"),
+ yaxis2=list(side="right",overlaying="y3"),
+ showlegend=TRUE)
+# Bottom left
+p3 <- plot_ly() %>% add_trace(x = c(1, 2, 3), y = c(2, 52, 62),type="scatter",mode="lines+markers",yaxis="y", name="yaxis5 data") %>%
+ add_trace(x = c(1, 2, 3), y = c(40, 50, 60),type="scatter",mode="lines+markers",yaxis="y2", name="yaxis6 data") %>%
+ layout(yaxis=list(side="left"),
+ yaxis2=list(side="right",overlaying="y5"),
+ showlegend=TRUE)
+# Bottom right
+p4 <-plot_ly() %>% add_trace(x = c(1, 2, 3), y = c(2, 52, 62),type="scatter",mode="lines+markers",yaxis="y", name="yaxis7 data") %>%
+ add_trace(x = c(1, 2, 3), y = c(40, 50, 60),type="scatter",mode="lines+markers",yaxis="y2", name="yaxis8 data") %>%
+ layout(yaxis=list(side="left"),
+ yaxis2=list(side="right",overlaying="y7"),
+ showlegend=TRUE)
+
+p <- subplot(p1,p2,p3,p4,nrows = 2, margin = 0.05)%>% layout(legend = list(x = 1.05, y = 1))
+p
+```
+
+## Multiple Axes
+
+Using Plotly for creating a figure with multiple axes
+
+```{r}
+library(plotly)
+
+fig <- plot_ly(width = 700)
+fig <- fig %>% add_trace(x = ~1:3, y = ~4:6, name = "yaxis1 data", mode = "lines+markers", type = "scatter")
+
+y2 <- list(
+ tickfont = list(color = "#ff7f0e"),
+ titlefont = list(color = "#ff7f0e"),
+ overlaying = "y",
+ side = "left",
+ anchor="free",
+ position=0.15,
+ title = "yaxis2 title")
+
+
+fig <- fig %>% add_trace(x = ~2:4, y = ~10*(4:6), name = "yaxis2 data", yaxis = "y2", mode = "lines+markers", type = "scatter")
+
+y3 <- list(
+ tickfont = list(color = "#d62728"),
+ titlefont = list(color = "#d62728"),
+ overlaying = "y",
+ side = "right",
+ title = "yaxis3 title")
+
+
+fig <- fig %>% add_trace(x = ~4:6, y = ~1000*(4:6), name = "yaxis3 data", yaxis = "y3", mode = "lines+markers", type = "scatter")
+
+y4 <- list(
+ tickfont = list(color = "#9467bd"),
+ titlefont = list(color = "#9467bd"),
+ overlaying = "y",
+ side = "right",
+ anchor="free",
+ position=0.85,
+ title = "yaxis4 title")
+
+
+fig <- fig %>% add_trace(x = ~5:7, y = ~10000*(4:6), name = "yaxis4 data", yaxis = "y4", mode = "lines+markers", type = "scatter")
+
+fig <- fig %>% layout(
+ title = "multiple y-axes example", yaxis2 = y2, yaxis3 = y3, yaxis4 = y4,
+ xaxis = list(title = '', domain = c(0.3, 0.7)),
+ yaxis = list(title="yaxis title",
+ tickfont = list(color = "#1f77b4"),
+ titlefont = list(color = "#1f77b4")
+ )
+)
+
+fig
+```
+
+### Reference
+All of the y-axis properties are found here: https://plotly.com/r/reference/layout/yaxis/. For more information on creating subplots see the [Subplots in R](https://plotly.com/r/subplot-charts/) section.
diff --git a/r/2021-08-12-figure-data-structure.rmd b/r/2021-08-12-figure-data-structure.rmd
new file mode 100644
index 00000000..8ad81b14
--- /dev/null
+++ b/r/2021-08-12-figure-data-structure.rmd
@@ -0,0 +1,227 @@
+---
+title: "The Figure Data Structure in R"
+
+---
+The structure of a figure - data, traces and layout explained.
+
+### Overview
+
+Plotly's R graphing library makes interactive, publication-quality graphs. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, and 3D (WebGL based) charts. Plotly.R is free and open source and you can view the source, report issues or contribute on GitHub. The rendering process uses the [Plotly.js JavaScript library](https://plotly.com/javascript/) under the hood. Figures can be represented in R either as lists or as instances of the `plotly` , and are serialized as text in [JavaScript Object Notation (JSON)](https://json.org/) before being passed to Plotly.js.
+
+
+Viewing the underlying data structure for any `plotly` object, can be done via `dput(fig)`.
+
+```{r}
+
+library(plotly)
+
+fig <- plot_ly() %>%
+ add_lines(x = c("a","b","c"), y = c(1,3,2))%>%
+ layout(title="sample figure", xaxis = list(title = 'x'), yaxis = list(title = 'y'))
+
+dput(fig$x)
+fig
+```
+
+### Accessing figure structures in Dash
+
+[Dash for R](https://dashr.plotly.com) is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
+
+Learn about how to install Dash for R at https://dashr.plot.ly/installation.
+
+Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument.
+
+
+```{r}
+library(dash)
+library(dashCoreComponents)
+library(dashHtmlComponents)
+library(plotly)
+
+fig <- plot_ly() %>%
+ add_lines(x = c("a","b","c"), y = c(1,3,2))%>%
+ layout(title="sample figure")
+
+app <- Dash$new()
+
+app$layout(
+ htmlDiv(
+ list(
+ dccGraph(id = 'graph', figure=fig),
+ htmlPre(
+ id='structure',
+ style = list(border = 'thin lightgrey solid',
+ overflowY = 'scroll',
+ height = '275px')
+ )
+ )
+ )
+)
+app$callback(
+ output(id = 'structure', property='children'),
+ params=list(input(id='graph', property='figure')),
+ function(fig_json) {
+ plotly_json <- function(p, ...) {
+ plotly:::to_JSON(plotly_build(p), ...)
+ }
+ jfig <- plotly_json(fig, pretty = TRUE)
+ return(jfig)
+ })
+
+
+```
+
+After executing this code, give app$run_server() in the console to start the dash.
+
+### Figures as Trees of Attributes
+
+Plotly.js supports inputs adhering to a well-defined schema, whose overall architecture is explained in this page and which is exhaustively documented in the [Figure Reference](https://plotly.com/r/reference/) (which is itself generated from a [machine-readable JSON representation of the schema](https://raw.githubusercontent.com/plotly/plotly.js/master/dist/plot-schema.json)). Figures are represented as trees with named nodes called "attributes".
+
+Attributes are referred to in text and in the [Figure Reference](https://plotly.com/r/reference/) by their names. For example `"layout = list(width = NULL)"` refers to the attribute whose key is `"width"` inside a list which is the value associated with a key `"layout"` at the root of the figure.
+
+When manipulating a `plotly` object, attributes can be set directly using R object attributes e.g. `fig.layout.title.font.family="Open Sans"` or using fig %>% layout(title = list(font = 'Open Sans')).
+
+When building a figure, it is *not necessary to populate every attribute* of every object. At render-time, the JavaScript layer will compute default values for each required unspecified attribute, depending upon the ones that are specified, as documented in the [Figure Reference](https://plotly.com/r/reference/). An example of this would be `layout.xaxis.range`, which may be specified explicitly, but if not will be computed based on the range of `x` values for every trace linked to that axis. The JavaScript layer will ignore unknown attributes or malformed values, although the `plotly` module provides R-side validation for attribute values.
+
+### The Top-Level `data` Attribute
+
+The first of the three top-level attributes of a figure is `data`, whose value must be a list referred to as "traces".
+
+* Each trace has one of more than 40 possible types (see below for a list organized by subplot type, including e.g. [`scatter`](https://plotly.com/r/line-and-scatter/), [`bar`](https://plotly.com/r/bar-charts/), [`pie`](https://plotly.com/r/pie-charts/), [`surface`](https://plotly.com/r/3d-surface-plots/), [`choropleth`](https://plotly.com/r/choropleth-maps/) etc), and represents a set of related graphical marks in a figure. Each trace must have a `type` attribute which defines the other allowable attributes.
+* Each trace is drawn on a single [subplot](https://plotly.com/r/subplots/) whose type must be compatible with the trace's type, or is its own subplot (see below).
+* Traces may have a single [legend](https://plotly.com/r/legend/) entry, with the exception of pie and funnelarea traces (see below).
+* Certain trace types support [continuous color, with an associated colorbar](https://plotly.com/r/colorscales/), which can be controlled by attributes either within the trace, or within the layout when using the [coloraxis attribute](https://plotly.com/r/reference/layout/coloraxis/).
+
+
+### The Top-Level `layout` Attribute
+
+The second of the three top-level attributes of a figure is `layout`, whose value is referred to in text as "the layout" and must be a list, containing attributes that control positioning and configuration of non-data-related parts of the figure such as:
+
+ * Dimensions and margins, which define the bounds of "paper coordinates" (see below)
+ * Title and [legend](https://plotly.com/r/legend/) (positionable in container and/or paper coordinates)
+ * [Color axes and associated color bars](https://plotly.com/r/colorscales/) (positionable in paper coordinates)
+ * Subplots of various types on which can be drawn multiple traces and which are positioned in paper coordinates:
+ * `xaxis`, `yaxis`, `xaxis2`, `yaxis3` etc: X and Y cartesian axes, the intersections of which are cartesian subplots
+ * `scene`, `scene2`, `scene3` etc: 3d scene subplots
+ * `ternary`, `ternary2`, `ternary3`, `polar`, `polar2`, `polar3`, `geo`, `geo2`, `geo3`, `mapbox`, `mapbox2`, `mabox3` etc: ternary, polar, geo or mapbox subplots
+ * Non-data marks which can be positioned in paper coordinates, or in data coordinates linked to 2d cartesian subplots:
+ * `annotations`: [textual annotations with or without arrows](https://plotly.com/r/text-and-annotations/)
+ * `shapes`: [lines, rectangles, ellipses or open or closed paths](https://plotly.com/r/shapes/)
+ * Controls which can be positioned in paper coordinates and which can trigger Plotly.js functions when interacted with by a user:
+ * `updatemenus`: [single buttons, toggles](https://plotly.com/r/custom-buttons/) and [dropdown menus](https://plotly.com/r/dropdowns/)
+ * `sliders`: [slider controls](https://plotly.com/r/sliders/)
+
+### The Top-Level `frames` Attribute
+
+The third of the three top-level attributes of a figure is `frames`, whose value must be a list that define sequential frames in an [animated plot](https://plotly.com/r/animations/). Each frame contains its own data attribute as well as other parameters. Animations are usually triggered and controlled via controls defined in layout.sliders and/or layout.updatemenus
+
+
+### Positioning With Paper, Container Coordinates, or Axis Domain Coordinates
+
+Various figure components configured within the layout of the figure support positioning attributes named `x` or `y`, whose values may be specified in "paper coordinates" (sometimes referred to as "plot fractions" or "normalized coordinates"). Examples include `layout.xaxis.domain` or `layout.legend.x` or `layout.annotation.x`.
+
+Positioning in paper coordinates is *not* done in absolute pixel terms, but rather in terms relative to a coordinate system defined with an origin `(0,0)` at `(layout.margin.l, layout.margin.b)` and a point `(1,1)` at `(layout.width-layout.margin.r, layout.height-layout.margin.t)` (note: `layout.margin` values are pixel values, as are `layout.width` and `layout.height`). Paper coordinate values less than 0 or greater than 1 are permitted, and refer to areas within the plot margins.
+
+To position an object in "paper" coordinates, the corresponding axis reference
+is set to `"paper"`. For instance a shape's `xref` attribute would be set to
+`"paper"` so that the `x` value of the shape refers to its position in paper
+coordinates.
+
+Note that the contents of the `layout.margin` attribute are by default computed based on the position and dimensions of certain items like the title or legend, and may be made dependent on the position and dimensions of tick labels as well when setting the `layout.xaxis.automargin` attribute to `True`. This has the effect of automatically increasing the margin values and therefore shrinking the physical area defined between the `(0,0)` and `(1,1)` points. Positioning certain items at paper coordinates less than 0 or greater than 1 will also trigger this behavior. The `layout.width` and `layout.height`, however, are taken as givens, so a figure will never grow or shrink based on its contents.
+
+The figure title may be positioned using "container coordinates" which have `(0,0)` and `(1,1)` anchored at the bottom-left and top-right of the figure, respectively, and therefore are independent of the values of layout.margin.
+
+Furthermore, shapes, annotations, and images can be placed relative to an axis's
+domain so that, for instance, an `x` value of `0.5` would place the object
+halfway along the x-axis, regardless of the domain as specified in the
+`layout.xaxis.domain` attribute. This behavior can be specified by adding
+`' domain'` to the axis reference in the axis referencing attribute of the object.
+For example, setting `yref = 'y2 domain'` for a shape will refer to the length
+and position of the axis named `y2`.
+
+### 2D Cartesian Trace Types and Subplots
+
+The most commonly-used kind of subplot is a [two-dimensional Cartesian subplot](https://plotly.com/r/axes/). Traces compatible with these subplots support `xaxis` and `yaxis` attributes whose values must refer to corresponding objects in the layout portion of the figure. For example, if `xaxis="x"`, and `yaxis="y"` (which is the default) then this trace is drawn on the subplot at the intersection of the axes configured under `layout.xaxis` and `layout.yaxis`, but if `xaxis="x2"` and `yaxis="y3"` then the trace is drawn at the intersection of the axes configured under `layout.xaxis2` and `layout.yaxis3`. Note that attributes such as `layout.xaxis` and `layout.xaxis2` etc do not have to be explicitly defined, in which case default values will be inferred. Multiple traces of different types can be drawn on the same subplot.
+
+X- and Y-axes support the `type` attribute, which enables them to represent [continuous values (`type="linear"`, `type="log"`)](https://plotly.com/r/axes/), temporal values (`type="date"`) or [categorical values (`type="category"`, `type="multicategory`)](https://plotly.com/r/bar-charts/#). Axes can also be overlaid on top of one another to create [dual-axis or multiple-axis charts](https://plotly.com/r/multiple-axes/). 2-d cartesian subplots lend themselves very well to creating "small multiples" figures, also known as facet or trellis plots.
+
+The following trace types are compatible with 2d-cartesian subplots via the `xaxis` and `yaxis` attributes:
+
+* scatter-like trace types: [`scatter`](https://plotly.com/r/line-and-scatter/) and [`scattergl`](https://plotly.com/r/webgl-vs-svg/), which can be used to draw [scatter plots](https://plotly.com/r/line-and-scatter/), [line plots and curves](https://plotly.com/r/line-charts/), [bubble charts](https://plotly.com/r/bubble-charts/), [dot plots](https://plotly.com/r/dot-plots/) and [filled areas](https://plotly.com/r/filled-area-plots/) and also support [error bars](https://plotly.com/r/error-bars/)
+* [`bar`](https://plotly.com/r/bar-charts/), [`funnel`](https://plotly.com/r/funnel-charts/), [`waterfall`](https://plotly.com/r/waterfall-charts/): bar-like trace types which can also be used to draw [timelines and Gantt charts](https://plotly.com/r/gantt/)
+* [`histogram`](https://plotly.com/r/histograms/): an *aggregating* bar-like trace type
+* [`box`](https://plotly.com/r/box-plots/#) and [`violin`](https://plotly.com/r/violin/): 1-dimensional distribution-like trace types
+* [`heatmap`](https://plotly.com/r/heatmaps/) and [`contour`](https://plotly.com/r/contour-plots/): matrix trace types
+* [`histogram2d`](https://plotly.com/r/2D-Histogram/) and [`histogram2dcontour`](https://plotly.com/r/2d-histogram-contour/): 2-dimensional distribution-like density trace types
+* [`ohlc`](https://plotly.com/r/ohlc-charts/) and [`candlestick`](https://plotly.com/r/candlestick-charts/): stock-like trace types
+* [`carpet`](https://plotly.com/r/carpet-plot/): a special trace type for building [carpet plots](https://plotly.com/r/carpet-plot/), in that other traces can use as subplots (see below)
+* [`splom`](https://plotly.com/r/splom/#): multi-dimensional scatter plots which implicitly refer to many 2-d cartesian subplots at once.
+
+
+### 3D, Polar and Ternary Trace Types and Subplots
+
+Beyond 2D cartesian subplots, figures can include [three-dimensional cartesian subplots](https://plotly.com/r/3d-charts/), [polar subplots](https://plotly.com/r/polar-chart/) and [ternary subplots](https://plotly.com/r/ternary-plots/). The following trace types support attributes named `scene`, `polar` or `ternary`, whose values must refer to corresponding objects in the layout portion of the figure i.e. `ternary="ternary2"` etc. Note that attributes such as `layout.scene` and `layout.ternary2` etc do not have to be explicitly defined, in which case default values will be inferred. Multiple traces of a compatible type can be placed on the same subplot.
+
+The following trace types are compatible with 3D subplots via the `scene` attribute, which contains special [camera controls](https://plotly.com/r/reference/layout/scene/#layout-scene-camera):
+
+* [`scatter3d`](https://plotly.com/r/3d-scatter-plots/), which can be used to draw [individual markers](https://plotly.com/r/3d-scatter-plots/), [lines and curves](https://plotly.com/r/3d-line-plots/)
+* [`surface`](https://plotly.com/r/3d-surface-plots/) and [`mesh`](https://plotly.com/r/3d-mesh/): 3d surface trace types
+* [`cone`](https://plotly.com/r/cone-plot/) and [`streamtube`](https://plotly.com/r/streamtube-plot/): 3d vector field trace types
+* [`volume`](https://plotly.com/r/reference/volume/) and [`isosurface`](https://plotly.com/r/3d-isosurface-plots/): 3d volume trace types
+
+The following trace types are compatible with polar subplots via the `polar` attribute:
+
+* scatter-like trace types: [`scatterpolar` and `scatterpolargl`](https://plotly.com/r/polar-chart/), which can be used to draw individual markers, [curves and filled areas (i.e. radar or spider charts)](https://plotly.com/r/radar-chart/)
+* [`barpolar`](https://plotly.com/r/polar-chart/)
+
+The following trace types are compatible with ternary subplots via the `ternary` attribute:
+
+* [`scatterternary`](https://plotly.com/r/ternary-plots/), which can be used to draw individual markers, [curves and filled areas](https://plotly.com/r/ternary-contour/)
+
+### Map Trace Types and Subplots
+
+Figures can include two different types of map subplots: [geo subplots for outline maps](https://plotly.com/r/choropleth-maps/#base-map-configuration) and [mapbox subplots for tile maps](https://plotly.com/r/mapbox-layers/). The following trace types support attributes named `geo` or `mapbox`, whose values must refer to corresponding objects in the layout i.e. `geo="geo2"` etc. Note that attributes such as `layout.geo2` and `layout.mapbox` etc do not have to be explicitly defined, in which case default values will be inferred. Multiple traces of a compatible type can be placed on the same subplot.
+
+The following trace types are compatible with geo subplots via the `geo` attribute:
+
+* [`scattergeo`](https://plotly.com/r/scatter-plots-on-maps/), which can be used to draw [individual markers](https://plotly.com/r/scatter-plots-on-maps/), [line and curves](https://plotly.com/r/lines-on-maps/) and filled areas on outline maps
+* [`choropleth`](https://plotly.com/r/choropleth-maps/): [colored polygons](https://plotly.com/r/choropleth-maps/) on outline maps
+
+The following trace types are compatible with mapbox subplots via the `mapbox` attribute:
+
+* [`scattermapbox`](https://plotly.com/r/scatter-plots-on-maps/), which can be used to draw [individual markers](https://plotly.com/r/scatter-plots-on-maps/), [lines and curves](https://plotly.com/r/lines-on-maps/) and [filled areas](https://plotly.com/r/filled-area-on-mapbox/) on tile maps
+* [`choroplethmapbox`](https://plotly.com/r/choropleth-maps/): colored polygons on tile maps
+* [`densitymapbox`](https://plotly.com/r/mapbox-density-heatmaps/): density heatmaps on tile maps
+
+### Traces Which Are Their Own Subplots
+
+Certain trace types cannot share subplots, and hence have no attribute to map to a corresponding subplot in the layout. Instead, these traces are their own subplot and support a `domain` attribute for position, which enables the trace to be positioned in paper coordinates (see below). With the exception of `pie` and `funnelarea`, such traces also do not support legends (see below)
+
+The following trace types are their own subplots and support a domain attribute:
+
+* [`pie`](https://plotly.com/r/pie-charts/) and [`funnelarea`](https://plotly.com/r/waterfall-charts/): one-level part-to-whole relationships with legend items
+* [`sunburst`](https://plotly.com/r/sunburst-charts/) and [`treemap`](https://plotly.com/r/treemaps/): hierarchical multi-level part-to-whole relationships
+* [`parcoords`](https://plotly.com/r/parallel-coordinates-plot/) and [`parcats`](https://plotly.com/r/reference/parcats/): continuous and categorical multidimensional figures with [parallel coordinates](https://plotly.com/r/parallel-coordinates-plot/) and [parallel sets](https://plotly.com/r/reference/parcats/)
+* [`sankey`](https://plotly.com/r/sankey-diagram/): [flow diagrams](https://plotly.com/r/sankey-diagram/)
+* [`table`](https://plotly.com/r/table/): [text-based tables](https://plotly.com/r/table/)
+* [`indicator`](https://plotly.com/r/reference/indicator/): big numbers, [gauges](https://plotly.com/r/gauge-charts/), and [bullet charts](https://plotly.com/r/bullet-charts/)
+
+### Carpet Trace Types and Subplots
+
+Certain trace types use [traces of type `carpet` as a subplot](https://plotly.com/r/carpet-plot/). These support a `carpet` attribute whose value must match the value of the `carpet` attribute of the `carpet` trace they are to be drawn on. Multiple compatible traces can be placed on the same `carpet` trace.
+
+The following trace types are compatible with `carpet` trace subplots via the `carpet` attribute:
+
+* [`scattercarpet`](https://plotly.com/r/carpet-scatter/), which can be used to draw individual markers, curves and filled areas
+* [`contourcarpet`](https://plotly.com/r/carpet-plot/)
+
+### Trace Types, Legends and Color Bars
+
+Traces of most types can be optionally associated with a single legend item in the [legend](https://plotly.com/r/legend/). Whether or not a given trace appears in the legend is controlled via the `showlegend` attribute. Traces which are their own subplots (see above) do not support this, with the exception of traces of type `pie` and `funnelarea` for which every distinct color represented in the trace gets a separate legend item. Users may show or hide traces by clicking or double-clicking on their associated legend item. Traces that support legend items also support the `legendgroup` attribute, and all traces with the same legend group are treated the same way during click/double-click interactions.
+
+The fact that legend items are linked to traces means that when using [discrete color](https://plotly.com/r/colorscales/), a figure must have one trace per color in order to get a meaningful legend.
+
+Traces which support [continuous color](https://plotly.com/r/colorscales/) can also be associated with color axes in the layout via the `coloraxis` attribute. Multiple traces can be linked to the same color axis. Color axes have a legend-like component called color bars. Alternatively, color axes can be configured within the trace itself.
+
+
+
diff --git a/r/2021-08-13-creating-updating-figures.rmd b/r/2021-08-13-creating-updating-figures.rmd
new file mode 100644
index 00000000..201944ab
--- /dev/null
+++ b/r/2021-08-13-creating-updating-figures.rmd
@@ -0,0 +1,399 @@
+## Creating and Updating Figures in R
+Creating and Updating Figures with Plotly's R graphing library
+
+The `plotly` R package exists to create, manipulate and [render](https://plotly.com/r/getting-started/#rendering-charts) graphical figures (i.e. charts, plots, maps and diagrams) represented by data structures also referred to as figures. The rendering process uses the [Plotly.js JavaScript library](https://plotly.com/javascript/) under the hood although R developers using this module very rarely need to interact with the Javascript library directly, if ever. Figures can be represented in R either as lists or as instances of the Plotly Figures, and are serialized as text in [JavaScript Object Notation (JSON)](https://json.org/) before being passed to Plotly.js.
+
+### Figures As Lists
+
+Figures can be represented as Lists and displayed using `plotly_build` function. The `fig` list in the example below describes a figure. It contains a single `bar` trace and a title.
+
+```{r}
+library(plotly)
+fig = list(
+ data = list(
+ list(
+ x = c(1, 2, 3),
+ y = c(1, 3, 2),
+ type = 'bar'
+ )
+ ),
+ layout = list(
+ title = 'A Figure Specified By R List'
+ )
+)
+# To display the figure defined by this list, use the plotly_build function
+plotly_build(fig)
+```
+
+### Plotly Figures
+
+The `plot_ly` function provides an automatically-generated hierarchy of classes that may be used to represent figures.
+
+`plot_ly` figures have several benefits compared to plain R Lists.
+
+1. `plot_ly` figures provide precise data validation. If you provide an invalid property name or an invalid property value as the key to a Plotly Figure, an exception will be raised with a helpful error message describing the problem. This is not the case if you use plain R lists to build your figures.
+2. `plot_ly` figures contain descriptions of each valid property as R docstrings. You can use these docstrings in the development environment of your choice to learn about the available properties as an alternative to consulting the online [Full Reference](https://plotly.com/r/reference/).
+3. Properties of `plot_ly` figures can be accessed using both dictionary-style key lookup (e.g. `fig$x`).
+4. `plot_ly` figures support higher-level convenience functions for making updates to already constructed figures (`.layout()`, `.add_trace()` etc).
+5. `plot_ly` figures support attached rendering and exporting functions that automatically invoke the appropriate functions.
+
+Below you can find an example of one way that the figure in the example above could be specified using a `plot_ly` figure instead of a list.
+
+```{r}
+library(plotly)
+
+fig <- plot_ly(x = c(1, 2, 3), y = c(1, 3, 2), type = 'bar')%>%
+ layout(title = 'A Plotly Figure')
+fig
+```
+
+##### Converting plot_ly figures To Lists and JSON
+
+`plot_ly` figures can be turned into their R List representation. You can also retrieve the JSON string representation of a plotly figure using the `fig.to_JSON()` method.
+
+```{r, attr.output='style="max-height: 200px;"'}
+library(plotly)
+library(jsonlite)
+fig <- plot_ly(x = c(1, 2, 3), y = c(1, 3, 2), type = 'bar')
+plotly_json <- function(p, ...) {
+ plotly:::to_JSON(plotly_build(p), ...)
+ }
+jfig <- plotly_json(fig, pretty = TRUE)
+
+listprint <- paste("List Representation of A plot_ly figure:",toString(fig),sep = "\n")
+cat(listprint[1])
+JSONprint <- paste("JSON Representation of A plot_ly figure:",jfig,sep = "\n")
+cat(JSONprint[1])
+```
+
+### Representing Figures in Dash
+
+[Dash for R](https://dashr.plotly.com/) is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
+
+Learn about how to install Dash for R at https://dashr.plot.ly/installation.
+
+Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument.
+
+```{r}
+library(dash)
+library(dashCoreComponents)
+library(dashHtmlComponents)
+library(plotly)
+
+fig <- plot_ly() %>%
+ add_lines(x = c("a","b","c"), y = c(1,3,2))%>%
+ layout(title="sample figure")
+
+app <- Dash$new()
+
+app$layout(
+ htmlDiv(
+ list(
+ dccGraph(id = 'graph', figure=fig),
+ htmlPre(
+ id='structure',
+ style = list(border = 'thin lightgrey solid',
+ overflowY = 'scroll',
+ height = '275px')
+ )
+ )
+ )
+)
+app$callback(
+ output(id = 'structure', property='children'),
+ params=list(input(id='graph', property='figure')),
+ function(fig_json) {
+ plotly_json <- function(p, ...) {
+ plotly:::to_JSON(plotly_build(p), ...)
+ }
+ jfig <- plotly_json(fig, pretty = TRUE)
+ return(jfig)
+ })
+#app$run_server()
+```
+
+Use `app$run_server()` to run the dash app.
+
+### Creating Figures
+
+This section summarizes several ways to create new `plot_ly` figures with the `plotly` graphing library.
+
+#### Plotly Scatter Plot
+
+```{r}
+library(plotly)
+data(iris)
+
+fig <- plot_ly(data = iris, x = ~Sepal.Width, y = ~Sepal.Length, color = ~Species,
+ type = "scatter", mode = "markers")%>%
+ layout(title="A Plotly Figure", legend=list(title=list(text='species')))
+fig
+```
+
+#### Make Subplots
+
+The `subplots()` function produces a `plot_ly` figure that is preconfigured with a grid of subplots that traces can be added to.
+
+```{r}
+library(plotly)
+
+fig1 <- plot_ly(y = c(4, 2, 1), type = "scatter", mode = "lines")
+fig2 <- plot_ly(y = c(2, 1, 3), type = "bar")
+
+fig <- subplot(fig1, fig2)
+fig
+```
+
+### Updating Figures
+
+Regardless of how a `plot_ly` figure was constructed, it can be updated by adding additional traces to it and modifying its properties.
+
+#### Adding Traces
+
+New traces can be added to a `plot_ly` figure using the `add_trace()` method. This method accepts a `plot_ly` figure trace and adds it to the figure. This allows you to start with an empty figure, and add traces to it sequentially.
+
+```{r}
+library(plotly)
+
+fig <- plot_ly()%>%
+ add_trace(x = c(1, 2, 3), y = c(1, 3, 2), type = 'bar')
+fig
+```
+
+```{r}
+library(plotly)
+data(iris)
+
+fig <- plot_ly()%>%
+ add_trace(data = iris, x = ~Sepal.Width, y = ~Sepal.Length, color = ~Species,
+ type = "scatter", mode = "markers")%>%
+ layout(title="Using The add_trace() method With A Plotly Figure", legend=list(title=list(text='species')))%>%
+ add_trace(x = c(2, 4), y = c(4, 8), type = "scatter", mode = "lines", line = list(color = 'grey')
+ , showlegend = FALSE)
+fig
+```
+
+#### Updating Figure Layouts
+
+`plot_ly` figures support an `style()` method that may be used to update multiple nested properties of a figure's layout.
+
+Here is an example of updating the font size of a figure's title using `style()`.
+
+```{r}
+library(plotly)
+
+fig <- plot_ly(x = c(1, 2, 3), y = c(1, 3, 2), type = 'bar')%>%
+ layout(title = list(text ='Using layout() With Plotly Figures', font = list(size = 17)))
+fig
+```
+
+
+#### Updating Traces
+
+`plot_ly` figures support an `style()` method that may be used to update multiple nested properties of one or more of a figure's traces.
+
+To show some examples, we will start with a figure that contains `bar` and `scatter` traces across two subplots.
+
+```{r}
+library(plotly)
+
+fig1 <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar', name = 'b', color = I("red")) %>%
+ add_trace(x = c(0,1, 2), y = c(4, 2, 3.5), type = 'scatter', mode = 'markers', name = 'a',
+ marker = list(size = 20, color = 'rgb(51, 204, 51)'))
+
+fig2 <- plot_ly(x = c(0,1, 2), y = c(1, 3, 2), type = 'bar', name = 'c', color = I("#33cc33")) %>%
+ add_trace(x = c(0,1, 2), y = c(2, 3.5, 4), type = 'scatter', mode = 'markers', name = 'd',
+ marker = list(size = 20, color = 'rgb(255, 0, 0)'))
+
+fig <- subplot(fig1, fig2)
+fig
+```
+
+Note that both `scatter` and `bar` traces have a `marker.color` property to control their coloring. Here is an example of using `style()` to modify the color of all traces.
+
+```{r}
+
+library(plotly)
+
+fig1 <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar', name = 'b', color = I("red")) %>%
+ add_trace(x = c(0,1, 2), y = c(4, 2, 3.5), type = 'scatter', mode = 'markers', name = 'a',
+ marker = list(size = 20, color = 'rgb(51, 204, 51)'))
+
+fig1 <- style(fig1, marker = list(size = 20, color = "blue"))
+
+fig2 <- plot_ly(x = c(0,1, 2), y = c(1, 3, 2), type = 'bar', name = 'c', color = I("#33cc33")) %>%
+ add_trace(x = c(0,1, 2), y = c(2, 3.5, 4), type = 'scatter', mode = 'markers', name = 'd',
+ marker = list(size = 20, color = 'rgb(255, 0, 0)'))
+
+fig2 <- style(fig1, marker = list(size = 20, color = "blue"))
+
+fig <- subplot(fig1, fig2)
+fig
+```
+
+The `style()` method supports a `traces` argument to control which traces should be updated. Only traces given will be updated. Here is an example of using a traces to only update the color of the `bar` traces.
+
+```{r}
+
+library(plotly)
+
+fig1 <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar', name = 'b', color = I("red")) %>%
+ add_trace(x = c(0,1, 2), y = c(4, 2, 3.5), type = 'scatter', mode = 'markers', name = 'a',
+ marker = list(size = 20, color = 'rgb(51, 204, 51)'))
+
+fig1 <- style(fig1, marker = list(color = "blue"), traces = c(1))
+
+fig2 <- plot_ly(x = c(0,1, 2), y = c(1, 3, 2), type = 'bar', name = 'c', color = I("#33cc33")) %>%
+ add_trace(x = c(0,1, 2), y = c(2, 3.5, 4), type = 'scatter', mode = 'markers', name = 'd',
+ marker = list(size = 20, color = 'rgb(255, 80, 80)'))
+
+fig2 <- style(fig2, marker = list(color = "blue"), traces = c(1))
+
+fig <- subplot(fig1, fig2)
+fig
+
+```
+
+### Overwrite Existing Properties When Using Update Methods
+
+`style()` will overwrite the prior value of existing properties, with the provided value.
+
+In the example below, the red color of markers is overwritten when updating `marker` in `style()`. Note that setting instead `opacity` with the magic underscore would not overwrite `marker_color` because properties would be overwritten starting only at the level of `marker.opacity`.
+
+```{r}
+library(plotly)
+
+fig <- plot_ly()%>%
+ add_trace(x = c(1, 2, 3), y = c(1, 3, 2), type = 'bar', marker = list(color = 'red'))
+
+style(fig, marker = list(opacity = 0.4))
+
+```
+
+#### Updating Figure Axes
+
+Plotly figures support `layout` method that may be used to update multiple nested properties of one or more of a figure's axes. Here is an example of using `layout` to disable the vertical grid lines across all subplots in a figure produced by Plotly.
+
+```{r}
+library(plotly)
+data(iris)
+
+fig <- iris%>%
+ group_by(Species) %>%
+ do(p=plot_ly(., x = ~Sepal.Width, y = ~Sepal.Length, color = ~Species, type = "scatter", mode = "markers")) %>%
+ subplot(nrows = 1, shareX = TRUE, shareY = TRUE)
+fig <- fig%>%
+ layout(title = "Updating x axis in a Plotly Figure", legend=list(title=list(text='species')),
+ xaxis = list(showgrid = F),
+ xaxis2 = list(showgrid = F),
+ xaxis3 = list(showgrid = F),
+ annotations = list(
+ list(
+ x = 0.16,
+ y = 0.95,
+ font = list(size = 10),
+ text = "species=setosa",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.5,
+ y = 0.95,
+ font = list(size = 10),
+ text = "species=versicolor",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ ),
+ list(
+ x = 0.85,
+ y = 0.95,
+ font = list(size = 10),
+ text = "species=virginica",
+ xref = "paper",
+ yref = "paper",
+ xanchor = "center",
+ yanchor = "bottom",
+ showarrow = FALSE
+ )))
+
+fig
+```
+
+### Other Update Methods
+
+Figures created with the plotly graphing library also support:
+
+ - the `images()` method in order to [update background layout images](https://plotly.com/r/displaying-images/),
+ - `annotations()` in order to [update annotations](https://plotly.com/r/text-and-annotations/),
+ - and `shapes()` in order to [update shapes](https://plotly.com/r/shapes/).
+
+#### Chaining Figure Operations
+
+All of the figure update operations described above are methods that return a reference to the figure being modified. This makes it possible to chain multiple figure modification operations together into a single expression.
+
+Here is an example of a chained expression that:
+
+ - sets the title font size using `layout.title.font.size`,
+ - disables vertical grid lines using `layout.xaxis`,
+ - updates the size and color of the markers and bar using `style()`,
+ - and then displaying the figure.
+
+```{r}
+library(plotly)
+
+t <- list(size = 15)
+
+fig <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar', name = 'b', color = I("red")) %>%
+ add_trace(x = c(0,1, 2), y = c(4, 2, 3.5), type = 'scatter', mode = 'markers', name = 'a',
+ marker = list(size = 10, color = 'rgb(51, 204, 51)'))
+#updates the size and color of the markers and bar
+fig <- style(fig, marker = list(size = 20, color = "blue"))
+
+fig <- style(fig, marker = list(color = "yellow"), traces = c(1))
+
+fig <- style(fig, marker = list(color = "yellow", line = list(color = 'rgb(8,48,107)',
+ width = 1.5)), traces = c(1))
+fig <- fig %>%
+ layout(title = list(text = "Chaining Multiple Figure Operations With A Plotly Figure",
+#setting the title font size
+ font = t),
+#disables vertical grid lines
+ xaxis = list(showgrid = F))
+#displaying the figure
+fig
+```
+
+#### Property Assignment
+
+Trace and layout properties can be updated using property assignment syntax. Here is an example of setting the figure title using property assignment.
+
+```{r}
+library(plotly)
+
+fig <- plot_ly()%>%
+ add_trace(x = c(1, 2, 3), y = c(1, 3, 2), type = 'bar')%>%
+ layout(title = 'Using Property Assignment Syntax With A Plotly Figure')
+fig <- style(fig,marker = list(line = list(color = 'lightblue', width = 0)))
+
+fig
+```
+
+And here is an example of updating the bar outline using property assignment.
+
+```{r}
+library(plotly)
+
+fig <- plot_ly()%>%
+ add_trace(x = c(1, 2, 3), y = c(1, 3, 2), type = 'bar')
+fig <- style(fig,marker = list(line = list(color = 'lightblue', width = 0)))
+fig$x$data[[1]]$marker$line$color <- 'black'
+fig$x$data[[1]]$marker$line$width <- 4
+
+fig
+```
diff --git a/r/2021-08-17-displaying-figures.Rmd b/r/2021-08-17-displaying-figures.Rmd
new file mode 100644
index 00000000..2f306a5f
--- /dev/null
+++ b/r/2021-08-17-displaying-figures.Rmd
@@ -0,0 +1,121 @@
+---
+title : "Displaying Figures in R"
+---
+Displaying Figures using Plotly's R graphing library
+
+# Displaying Figures
+
+Plotly's R graphing library, `plotly`, gives you a wide range of options for how and where to display your figures.
+
+In general, there are four different approaches you can take in order to display `plotly` figures:
+
+ 1. Using the `renderers` framework in the context of a script or notebook (the main topic of this page)
+ 2. Using [Dash](https://dashr.plotly.com) in a web app context
+ 3. By exporting to an HTML file and loading that file in a browser immediately or later
+ 4. By [rendering the figure to a static image file using Kaleido](https://plotly.com/r/static-image-export/) such as PNG, JPEG, SVG, PDF or EPS and loading the resulting file in any viewer
+
+Each of the first two approaches is discussed below.
+
+### Displaying Figures Using The `renderers` Framework
+
+The renderers framework is a flexible approach for displaying `plotly` figures in a variety of contexts. To display a figure using the renderers framework, you call the `print()` method on a graph object figure. It will display the figure using the current default renderer(s).
+
+```{r}
+
+library(plotly)
+
+fig <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar') %>%
+ layout(title = 'A Figure Displayed with print(fig)')
+
+print(fig)
+```
+
+In most situations, you can omit the call to `print()` and allow the figure to display itself.
+
+```{r}
+
+library(plotly)
+
+fig <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar') %>%
+ layout(title = 'A Figure Displaying Itself')
+
+fig
+```
+
+> To be precise, figures will display themselves using the current default renderer when the last expression in a cell must evaluate to a figure.
+
+**In many contexts, an appropriate renderer will be chosen automatically and you will not need to perform any additional configuration.**
+
+Next, we will show how to configure the default renderer. After that, we will describe all of the built-in renderers and discuss why you might choose to use each one.
+
+
+#### Overriding The Default Renderer
+It is also possible to override the default renderer temporarily by passing 'toWebGL()' to the fig. Here is an example of displaying a figure using the `webgl` renderer (described below) without changing the default renderer.
+
+```{r}
+
+library(plotly)
+
+fig <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar') %>%
+ layout(title = "A Figure Displayed with 'webgl' Renderer")
+
+fig <- fig %>% toWebGL()
+
+fig
+
+```
+
+
+##### Other Miscellaneous Renderers
+
+###### JSON
+In editors that support it , this renderer displays the JSON representation of a figure in a collapsible interactive tree structure. This can be very useful for examining the structure of complex figures. We have to use the function toJSON() to the figure.
+
+##### Multiple Renderers
+You can specify the multiple renderers by adding their respective functions separately. This is useful when writing code that needs to support multiple contexts.
+
+
+
+### Displaying figures in Dash
+
+[Dash for R](https://dashr.plotly.com) is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
+
+Learn about how to install Dash for R at https://dashr.plot.ly/installation.
+
+Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument.
+
+
+```{r}
+
+library(dash)
+library(dashCoreComponents)
+library(dashHtmlComponents)
+library(plotly)
+
+fig <- plot_ly(x = c(0,1, 2), y = c(2, 1, 3), type = 'bar') %>%
+ layout(title = 'Native Plotly rendering in Dash')
+
+app <- Dash$new()
+
+app$layout(
+ htmlDiv(
+ list(
+ dccGraph(id = 'graph', figure = fig)
+ )
+ )
+)
+
+```
+
+After executing this code, give app$run_server() in the console to start the dash.
+
+
+## Performance
+
+No matter the approach chosen to display a figure, the figure data structure is first (automatically, internally) serialized into a JSON string before being transferred from the R context to the browser (or to an HTML file first) or [to Kaleido for static image export](https://plotly.com/r/static-image-export/).
+
+*New in v5.0*
+
+The default JSON serialization mechanism can be slow for figures with many data points or with large arrays or data frames. **If [the `orjson` package](https://github.com/ijl/orjson) is installed**, `plotly` will use that instead of the built-in `json` package, which can lead to **5-10x** speedups for large figures.
+
+Once a figure is serialized to JSON, it must be rendered by a browser, either immediately in the user's browser, at some later point if the figure is exported to HTML, or immediately in Kaleido's internal headless browser for static image export. Rendering time is generally proportional to the total number of data points in the figure, the number of traces and the number of subplots. In situations where rendering performance is slow, we recommend considering [the use of `plotly` WebGL traces](https://plotly.com/r/webgl-vs-svg/) to exploit GPU-accelerated rendering in the browser to render the figure.
\ No newline at end of file