diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..bc837152 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,43 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at accounts@plot.ly. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.4, available at [http://contributor-covenant.org/version/1/4](http://contributor-covenant.org/version/1/4/), and may also be found online at . diff --git a/DESCRIPTION b/DESCRIPTION index 5f5df775..96dd5447 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,6 @@ -Package: Plotly's R graphing library. +Package: Plotly's R graphing library. Imports: geomorph, - maptools, rjson, dplyr, quantmod, diff --git a/README.md b/README.md index 34e317a6..d1cd6f47 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,8 @@ # plotly.r-docs The documentation for Ploty's R graphing library. + +
+ + Maintained by the Plotly Community + +
diff --git a/ggplot2/2021-08-04-legend.Rmd b/ggplot2/2021-08-04-legend.Rmd index 635d1b51..8b241d85 100644 --- a/ggplot2/2021-08-04-legend.Rmd +++ b/ggplot2/2021-08-04-legend.Rmd @@ -26,7 +26,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot() ggplotly(p) @@ -46,10 +46,10 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot() -p + theme(legend.position="bottom") +p <- p + theme(legend.position="bottom") ggplotly(p) ``` @@ -62,10 +62,10 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot() -p + theme(legend.position = c(0.8, 0.2)) +p <- p + theme(legend.position = c(0.8, 0.2)) ggplotly(p) ``` @@ -83,12 +83,12 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot() -p <- p + theme(legend.title = element_text(colour="red", size=10, +p <- p + theme(legend.title = element_text(colour="red", size=10, face="italic")) -p <- p + theme(legend.text = element_text(colour="blue", size=10, +p <- p + theme(legend.text = element_text(colour="blue", size=10, face="bold")) ggplotly(p) @@ -106,11 +106,11 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot() p <- p + theme(legend.background = element_rect(fill="lightblue", - size=0.5, linetype="solid", + size=0.5, linetype="solid", colour ="red")) ggplotly(p) @@ -128,10 +128,10 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot() -p + scale_x_discrete(limits=c("2", "0.5", "1")) +p <- p + scale_x_discrete(limits=c("2", "0.5", "1")) ggplotly(p) ``` @@ -149,7 +149,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot() p <- p + theme(legend.title = element_blank()) diff --git a/ggplot2/2021-08-04-log-plot.Rmd b/ggplot2/2021-08-04-log-plot.Rmd index da8a4370..062ed3e7 100644 --- a/ggplot2/2021-08-04-log-plot.Rmd +++ b/ggplot2/2021-08-04-log-plot.Rmd @@ -26,7 +26,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(cars, aes(x = speed, y = dist)) + +p <- ggplot(cars, aes(x = speed, y = dist)) + geom_point() p <- p + scale_x_continuous(trans = 'log2') + @@ -46,13 +46,13 @@ library(scales) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(cars, aes(x = speed, y = dist)) + +p <- ggplot(cars, aes(x = speed, y = dist)) + geom_point() p <- p + scale_x_continuous(trans = 'log2') + scale_y_continuous(trans = 'log2') -p + scale_y_continuous(trans = log2_trans(), +p <- p + scale_y_continuous(trans = log2_trans(), breaks = trans_breaks("log2", function(x) 2^x), labels = trans_format("log2", math_format(2^.x))) @@ -71,7 +71,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(cars, aes(x = speed, y = dist)) + +p <- ggplot(cars, aes(x = speed, y = dist)) + geom_point() p <- p + scale_y_log10() diff --git a/ggplot2/2021-08-04-network-graphs.Rmd b/ggplot2/2021-08-04-network-graphs.Rmd deleted file mode 100644 index a889a9eb..00000000 --- a/ggplot2/2021-08-04-network-graphs.Rmd +++ /dev/null @@ -1,287 +0,0 @@ ---- -description: How to make Network Graphs in ggplot2 with Plotly. -name: Network Graphs -permalink: ggplot2/network-graphs/ -thumnail_github: network-graphs.png -layout: base -language: ggplot2 -display_as: scientific -page_type: u-guide -order: 12 -output: - html_document: - keep_md: true ---- - -```{r, echo = FALSE, message=FALSE} -knitr::opts_chunk$set(message = FALSE, warning=FALSE) -``` - -## Random graph - -Let’s start with an undirected Bernoulli random graph, with 10 nodes named “a, b, …, i, j”, and a rather high likelihood of an edge to exist between them: - -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -# vertex names -network.vertex.names(net) = letters[1:10] - -p <- ggnet2(net) - - -ggplotly(p) -``` -The `net` argument is the only compulsory argument of `ggnet2`. It can be a `network` object or any object that can be coerced to that class through its `edgeset.constructors` functions, such as adjacency matrixes, incidence matrixes and edge lists. - -If the `intergraph` package is installed, `net` can also be an `igraph` one-mode network object, which is the only type of network that the package can convert from the `igraph` to the `network` class. - - - -## Node color and size - -The most basic properties that one might want to change at that stage are the size and color of the nodes, or the size and color of the edges. Let’s modify each of these properties: - -```{r} -library(plotly) -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -# vertex names -network.vertex.names(net) = letters[1:10] - -p <- ggnet2(net, node.size = 6, node.color = "black", edge.size = 1, edge.color = "grey") - -ggplotly(p) -``` -The vertex-related arguments of `ggnet2` start with `node`, and its edge-related arguments start with edge. The `node.color` and node.size arguments can be abbreviated: -`ggnet2(net, size = 6, color = "black", edge.size = 1, edge.color = "grey")` - -It also possible to pass a vector of node colors directly to `ggnet2`, as long as it has the same number of elements as the network has nodes: - - -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -# vertex names -network.vertex.names(net) = letters[1:10] - -p <- ggnet2(net, size = 6, color = rep(c("tomato", "steelblue"), 5)) - -ggplotly(p) -``` -The color, shape, size and transparency of nodes can all be set through these basic methods, or by passing a vertex attribute to them. Let’s first see how to position the nodes. - - - -## Node colors - -Let’s now assign a vertex attribute called phono, which indicates whether the name of the vertex is a vowel or a consonant. -This attribute can be passed to `ggnet2` to indicate that the nodes belong to a group. All the user has to do is to pass the name of the vertex attribute to the color argument, which will find it in the list of vertex attributes and use it to map the colors of the nodes: - -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -net %v% "phono" = ifelse(letters[1:10] %in% c("a", "e", "i"), "vowel", "consonant") - -p <- ggnet2(net, color = "phono") - -ggplotly(p) -``` -By default, `ggnet2` assigns a grayscale color to each group. To modify this behavior, let’s review three different options. The first one consists in “hard-coding” the colors into the graph by assigning them to a vertex attribute, and then in passing this attribute to `ggnet2`: - -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -net %v% "phono" = ifelse(letters[1:10] %in% c("a", "e", "i"), "vowel", "consonant") -net %v% "color" = ifelse(net %v% "phono" == "vowel", "steelblue", "tomato") - -p <- ggnet2(net, color = "color") - -ggplotly(p) -``` - -`ggnet2` returns a `ggplot` object, so the underlying data can be accessed by requesting the `data` component of the plot. The structure of that component always contains the following columns, which match the names of `ggplot2` arguments. -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -net %v% "phono" = ifelse(letters[1:10] %in% c("a", "e", "i"), "vowel", "consonant") -net %v% "color" = ifelse(net %v% "phono" == "vowel", "steelblue", "tomato") - -ggnet2(net, color = "phono", size = 1:10)$data -``` - -This means that you can append any `ggplot2` component to the graph by passing additional aesthetics to it, which allows for a fair amount of “plot hacking”. In this example, we use `ggnet2` to get the basic data structure in place, while sizing the nodes to 0. The nodes are then plotted manually, by overlaying several `geom` objects: -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -net %v% "phono" = ifelse(letters[1:10] %in% c("a", "e", "i"), "vowel", "consonant") -net %v% "color" = ifelse(net %v% "phono" == "vowel", "steelblue", "tomato") - -p <- ggnet2(net, color = "phono", palette = "Set1", size = 0) + - geom_point(aes(color = color), size = 12, color = "white") + - geom_point(aes(color = color), size = 12, alpha = 0.5) + - geom_point(aes(color = color), size = 9) + - geom_text(aes(label = toupper(substr(color, 1, 1))), color = "white", fontface = "bold") + - guides(color = FALSE) - -ggplotly(p) -``` - - -## Node size - -It is common to size the nodes of a network by their centrality or by some other indicator of interest. Just like its `color` argument, the `size` argument of `ggnet2` can take a single numeric value, a vector of values, or a vertex attribute: - -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -net %v% "phono" = ifelse(letters[1:10] %in% c("a", "e", "i"), "vowel", "consonant") -net %v% "color" = ifelse(net %v% "phono" == "vowel", "steelblue", "tomato") - -p <- ggnet2(net, size = "phono", size.palette = c("vowel" = 10, "consonant" = 1)) - -ggplotly(p) -``` - -When the `size` attribute is not a single numeric value, the maximum size of the nodes is determined by the `max_size` argument, just like in the `scale_size_area` controller of `ggplot2`, which `ggnet2` emulates to compute the relative size of the nodes: - -`ggnet2(net, size = sample(0:2, 10, replace = TRUE), max_size = 9)` - -`ggnet2` can also size nodes by calculating their in-degree, out-degree, or total (Freeman) degree, using the `degree` function of the `sna` package. All the user has to do is to pass the `indegree`, `outdegree`, or `freeman` option to the `weight` argument (`degree` is also understood, and is equivalent to `freeman`). - -`ggnet2` gives the user further control over the node size by providing a quick way to cut the node sizes into quantiles, using the `size.cut` argument. If set to `TRUE`, it defaults to quartiles, but any numeric value above 1 is acceptable: - - -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -net %v% "phono" = ifelse(letters[1:10] %in% c("a", "e", "i"), "vowel", "consonant") -net %v% "color" = ifelse(net %v% "phono" == "vowel", "steelblue", "tomato") - -p <- ggnet2(net, size = "degree", size.cut = 3) - -ggplotly(p) -``` - - - - -## Adding labels - -Through the `label` argument, `ggnet2` can label the nodes of a network by using their vertex names, another vertex attribute, or any other vector of labels. - -The size of the labels, which is automatically set to half of the node size, is controlled by the `label.size` argument, their color by the `label.color` argument, and their level of transparency by the `label.alpha` argument: - -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -p <-ggnet2(net, size = 12, label = TRUE, label.alpha = 0.75, label.size = 5, color = "black", label.color = "white") - -ggplotly(p) -``` - - - -## Changing shapes - -The shapes and transparency of the nodes can be set exactly like the color and size of the nodes, either through a single value, a vector of (numeric) values, or a vertex attribute. This allows to create nodes that can be distinguished even in the plot loses its colors: -```{r} -library(plotly) -library(ggnet) -library(network) -library(sna) -library(ggplot2) - -# random graph -net = rgraph(10, mode = "graph", tprob = 0.5) -net = network(net, directed = FALSE) - -net %v% "phono" = ifelse(letters[1:10] %in% c("a", "e", "i"), "vowel", "consonant") -net %v% "color" = ifelse(net %v% "phono" == "vowel", "steelblue", "tomato") - - -p <-ggnet2(net, color = "phono", shape = "phono") - -ggplotly(p) -``` - - \ No newline at end of file diff --git a/ggplot2/2021-08-04-radar-chart.Rmd b/ggplot2/2021-08-04-radar-chart.Rmd index 79496517..767e076b 100644 --- a/ggplot2/2021-08-04-radar-chart.Rmd +++ b/ggplot2/2021-08-04-radar-chart.Rmd @@ -19,22 +19,22 @@ knitr::opts_chunk$set(message = FALSE, warning=FALSE) ## Default radar plot -Radar charts are also called Spider or Web or Polar charts. +Radar charts are also called Spider or Web or Polar charts. Input data format is very specific. Each row must be an entity. Each column is a quantitative variable. First 2 rows provide the min and the max that will be used for each variable. Once you have this format, the radarchart() function makes all the job for you. -```{r} +```{r eval=FALSE} library(plotly) library(ggplot2) library(fmsb) - + data <- as.data.frame(matrix( sample( 2:20 , 10 , replace=T) , ncol=10)) colnames(data) <- c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" ) - + data <- rbind(rep(20,10) , rep(0,10) , data) - + p <- radarchart(data) ggplotly(p) @@ -46,19 +46,19 @@ ggplotly(p) ## Adding style -```{r} +```{r eval=FALSE} library(plotly) library(fmsb) - + data <- as.data.frame(matrix( sample( 2:20 , 10 , replace=T) , ncol=10)) colnames(data) <- c("math" , "english" , "biology" , "music" , "R-coding", "data-viz" , "french" , "physic", "statistic", "sport" ) data <- rbind(rep(20,10) , rep(0,10) , data) -p <- radarchart( data , axistype=1 , - pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 , +p <- radarchart( data , axistype=1 , + pcol=rgb(0.2,0.5,0.5,0.9) , pfcol=rgb(0.2,0.5,0.5,0.5) , plwd=4 , cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,20,5), cglwd=0.8, - vlcex=0.8 + vlcex=0.8 ) ggplotly(p) @@ -69,10 +69,10 @@ ggplotly(p) ## Plotting multiple groups -```{r} +```{r eval=FALSE} library(plotly) library(fmsb) - + data <- as.data.frame(matrix( sample( 0:20 , 15 , replace=F) , ncol=5)) colnames(data) <- c("math" , "english" , "biology" , "music" , "R-coding" ) rownames(data) <- paste("mister" , letters[1:3] , sep="-") @@ -85,10 +85,10 @@ ggplotly(p) ``` Adding style: -```{r} +```{r eval=FALSE} library(plotly) library(fmsb) - + data <- as.data.frame(matrix( sample( 0:20 , 15 , replace=F) , ncol=5)) colnames(data) <- c("math" , "english" , "biology" , "music" , "R-coding" ) rownames(data) <- paste("mister" , letters[1:3] , sep="-") @@ -98,10 +98,10 @@ data <- rbind(rep(20,5) , rep(0,5) , data) colors_border=c( rgb(0.2,0.5,0.5,0.9), rgb(0.8,0.2,0.5,0.9) , rgb(0.7,0.5,0.1,0.9) ) colors_in=c( rgb(0.2,0.5,0.5,0.4), rgb(0.8,0.2,0.5,0.4) , rgb(0.7,0.5,0.1,0.4) ) -p <- radarchart( data , axistype=1 , +p <- radarchart( data , axistype=1 , pcol=colors_border , pfcol=colors_in , plwd=4 , plty=1, cglcol="grey", cglty=1, axislabcol="grey", caxislabels=seq(0,20,5), cglwd=0.8, - vlcex=0.8 + vlcex=0.8 ) legend(x=0.7, y=1, legend = rownames(data[-c(1,2),]), bty = "n", pch=20 , col=colors_in , text.col = "grey", cex=1.2, pt.cex=3) diff --git a/ggplot2/2021-08-04-splom.Rmd b/ggplot2/2021-08-04-splom.Rmd index 0c0705b9..6a8b5d1a 100644 --- a/ggplot2/2021-08-04-splom.Rmd +++ b/ggplot2/2021-08-04-splom.Rmd @@ -26,12 +26,12 @@ Scatterplots of each pair of numeric variable are drawn on the left part of the ```{r} library(plotly) library(GGally) - -data <- data.frame( var1 = 1:100 + rnorm(100,sd=20), v2 = 1:100 + rnorm(100,sd=27), v3 = rep(1, 100) + rnorm(100, sd = 1)) -data$v4 = data$var1 ** 2 -data$v5 = -(data$var1 ** 2) - -p <- ggpairs(data, title="correlogram with ggpairs()") + +data <- data.frame( var1 = 1:100 + rnorm(100,sd=20), v2 = 1:100 + rnorm(100,sd=27), v3 = rep(1, 100) + rnorm(100, sd = 1)) +data$v4 = data$var1 ** 2 +data$v5 = -(data$var1 ** 2) + +p <- ggpairs(data, title="correlogram with ggpairs()") ggplotly(p) ``` @@ -46,14 +46,14 @@ he `ggcorr()` function allows to visualize the correlation of each pair of varia ```{r} library(plotly) library(GGally) - -data <- data.frame( var1 = 1:100 + rnorm(100,sd=20), v2 = 1:100 + rnorm(100,sd=27), v3 = rep(1, 100) + rnorm(100, sd = 1)) -data$v4 = data$var1 ** 2 -data$v5 = -(data$var1 ** 2) - -p <- ggcorr(data, method = c("everything", "pearson")) - -p + +data <- data.frame( var1 = 1:100 + rnorm(100,sd=20), v2 = 1:100 + rnorm(100,sd=27), v3 = rep(1, 100) + rnorm(100, sd = 1)) +data$v4 = data$var1 ** 2 +data$v5 = -(data$var1 ** 2) + +p <- ggcorr(data, method = c("everything", "pearson")) + +ggplotly(p) ``` @@ -64,10 +64,10 @@ It is possible to use `ggplot2` aesthetics on the chart, for instance to color e ```{r} library(plotly) library(GGally) - + data(flea) -p <- ggpairs(flea, columns = 2:4, ggplot2::aes(colour=species)) +p <- ggpairs(flea, columns = 2:4, ggplot2::aes(colour=species)) ggplotly(p) ``` @@ -82,7 +82,7 @@ Change the type of plot used on each part of the `correlogram`. This is done wit ```{r} library(plotly) library(GGally) - + data(tips, package = "reshape") p <- ggpairs( @@ -91,7 +91,7 @@ p <- ggpairs( lower = list(continuous = "points", combo = "dot_no_facet") ) -p +ggplotly(p) ``` \ No newline at end of file diff --git a/ggplot2/2021-08-04-strip-charts.Rmd b/ggplot2/2021-08-04-strip-charts.Rmd index 3bce6933..0ca2d6ee 100644 --- a/ggplot2/2021-08-04-strip-charts.Rmd +++ b/ggplot2/2021-08-04-strip-charts.Rmd @@ -26,10 +26,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -ggplot(ToothGrowth, aes(x=dose, y=len)) + - geom_jitter() - -p<-ggplot(ToothGrowth, aes(x=dose, y=len)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_jitter(position=position_jitter(0.2)) p <- p + coord_flip() @@ -48,7 +45,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_jitter(position=position_jitter(0.2), cex=1.2) ggplotly(p) @@ -65,7 +62,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_jitter(position=position_jitter(0.2), shape=17) ggplotly(p) @@ -83,7 +80,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_jitter(position=position_jitter(0.2), cex=1.2) p <- p + stat_summary(fun.y=mean, geom="point", shape=18, size=3, color="red") @@ -99,9 +96,9 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_jitter(position=position_jitter(0.2)) -p + stat_summary(fun.data=mean_sdl, mult=1, +p <- p + stat_summary(fun.data=mean_sdl, mult=1, geom="pointrange", color="red") ggplotly(p) @@ -114,7 +111,7 @@ You can change the representation of the statistics by changing `geom`, for exam ## Add box plot -To add a box plot you can use `geom_boxplot()`. Likewise, you can add a notched boxplot with `geom_boxplot(notch = TRUE)` and a violin plot with `geom_violin(trim = FALSE)`. +To add a box plot you can use `geom_boxplot()`. Likewise, you can add a notched boxplot with `geom_boxplot(notch = TRUE)` and a violin plot with `geom_violin(trim = FALSE)`. ```{r} library(plotly) @@ -122,7 +119,7 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot()+ geom_jitter(position=position_jitter(0.2)) @@ -153,10 +150,10 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -p <- ggplot(ToothGrowth, aes(x=dose, y=len, color=dose, shape=dose)) + +p <- ggplot(ToothGrowth, aes(x=dose, y=len, color=dose, shape=dose)) + geom_jitter(position=position_jitter(0.2))+ labs(title="Plot of length by dose",x="Dose (mg)", y = "Length") -p + theme_classic() +p <- p + theme_classic() ggplotly(p) ``` diff --git a/ggplot2/2021-08-04-treemaps.Rmd b/ggplot2/2021-08-04-treemaps.Rmd index 91108df6..250183e8 100644 --- a/ggplot2/2021-08-04-treemaps.Rmd +++ b/ggplot2/2021-08-04-treemaps.Rmd @@ -31,8 +31,6 @@ library(ggplot2) p <- ggplot(G20, aes(area = gdp_mil_usd, fill = hdi)) + geom_treemap() - -p ``` This plot isn’t very useful without the knowing what country is represented by each tile. `geom_treemap_text()` can be used to add a text label to each tile. It uses the `ggfittext` package to resize the text so it fits the tile. In addition to standard text formatting aesthetics you would use in `geom_text()`, like fontface or colour, we can pass additional options specific for `ggfittext`. For example, we can place the text in the centre of the tile with place = "centre", and expand it to fill as much of the tile as possible with grow = TRUE. @@ -52,8 +50,6 @@ p <- ggplot(G20, aes(area = gdp_mil_usd, fill = hdi, label = country)) + geom_treemap() + geom_treemap_text(fontface = "italic", colour = "white", place = "centre", grow = TRUE) - -p ``` Note that several tiles in the top right corner have no labels. `geom_treemap_text()` will hide text labels that cannot fit a tile without being shrunk below a minimum size, by default 4 points. This can be adjusted with the min.size argument. @@ -77,8 +73,6 @@ p <- ggplot(G20, aes(area = gdp_mil_usd, fill = hdi, label = country, geom_treemap_subgroup_text(place = "centre", grow = T, alpha = 0.5, colour = "black", fontface = "italic", min.size = 0) + geom_treemap_text(colour = "white", place = "topleft", reflow = T) - -p ``` Up to three nested levels of subgrouping are supported with the subgroup2 and subgroup3 aesthetics. Borders and text labels for these subgroups can be drawn with `geom_treemap_subgroup2_border()`, etc. Note that `ggplot2` draws plot layers in the order that they are added. This means it is possible to accidentally hide one layer of subgroup borders with another. Usually, it’s best to add the border layers in order from deepest to shallowest, i.e. `geom_treemap_subgroup3_border()` then `geom_treemap_subgroup2_border()` then `geom_treemap_subgroup_border()`. @@ -107,8 +101,6 @@ p <- ggplot(G20, aes(area = 1, label = country, subgroup = hemisphere, ) + geom_treemap_subgroup3_text(place = "top", colour = "blue", alpha = 0.5) + geom_treemap_text(colour = "white", place = "middle", reflow = T) - -p ``` As demonstrated, there is no assurance that the resulting plot will look good. diff --git a/r/2015-07-30-text-and-annotations.Rmd b/r/2015-07-30-text-and-annotations.Rmd index 6fb5c319..c5d70dbd 100644 --- a/r/2015-07-30-text-and-annotations.Rmd +++ b/r/2015-07-30-text-and-annotations.Rmd @@ -64,7 +64,7 @@ fig ### Controlling text fontsize with uniformtext -For the [pie](/r/pie-charts), [bar](/r/bar-charts), [sunburst](/r/sunburst-charts) and [treemap](/r/treemap-charts) traces, it is possible to force all the text labels to have the same size thanks to the `uniformtext` layout parameter. The `minsize` attribute sets the font size, and the `mode` attribute sets what happens for labels which cannot fit with the desired fontsize: either `hide` them or `show` them with overflow. +For the [pie](/r/pie-charts), [bar](/r/bar-charts), [sunburst](/r/sunburst-charts) and [treemap](/r/treemaps) traces, it is possible to force all the text labels to have the same size thanks to the `uniformtext` layout parameter. The `minsize` attribute sets the font size, and the `mode` attribute sets what happens for labels which cannot fit with the desired fontsize: either `hide` them or `show` them with overflow. ```{r} library(plotly) @@ -228,10 +228,10 @@ library(plotly) fig <- plot_ly() fig <- fig %>% add_trace( - x = c("2017-01-01", "2017-02-10", "2017-03-20"), - y = c("A", "B", "C"), - z = c(1, 1000, 100000), - name = "z", + x = c("2017-01-01", "2017-02-10", "2017-03-20"), + y = c("A", "B", "C"), + z = c(1, 1000, 100000), + name = "z", type = "scatter3d" ) fig <- fig %>% layout( diff --git a/r/2016-06-17-3d-tri-surf.Rmd b/r/2016-06-17-3d-tri-surf.Rmd index a312c635..4acf0c24 100644 --- a/r/2016-06-17-3d-tri-surf.Rmd +++ b/r/2016-06-17-3d-tri-surf.Rmd @@ -86,44 +86,3 @@ fig <- plot_ly( fig ``` - -### Maps - -```{r} -#devtools::install_github("hypertidy/anglr") -library(anglr) -library(maptools) -library(plotly) -data(wrld_simpl) - -map1 <- subset(wrld_simpl, - NAME %in% c("Indonesia", "Papua New Guinea", "New Zealand", "Australia")) -## DEL model (like TRI in silicate) -delmesh <- anglr::globe(anglr::DEL(map1, max_area = 0.5)) -mesh <- as.mesh3d(delmesh) - - -# plot point cloud -x <- mesh$vb[1,] -y <- mesh$vb[2, ] -z <- mesh$vb[3,] -m <- matrix(c(x,y,z), ncol=3, dimnames=list(NULL,c("x","y","z"))) - -# colours in z don't make sense here, need to map object aesthetics above -zmean <- apply(t(mesh$it),MARGIN=1,function(row){mean(m[row,3])}) - -library(scales) -facecolor = colour_ramp( - brewer_pal(palette="RdBu")(9) -)(rescale(x=zmean)) - -fig <- plot_ly( - x = x, y = y, z = z, - i = mesh$it[1,]-1, j = mesh$it[2,]-1, k = mesh$it[3,]-1, - facecolor = facecolor, - type = "mesh3d" -) - -fig -``` -Inspired by Michael Sumner \ No newline at end of file diff --git a/r/2017-01-13-mixed-subplot.Rmd b/r/2017-01-13-mixed-subplot.Rmd deleted file mode 100644 index 5eca69d6..00000000 --- a/r/2017-01-13-mixed-subplot.Rmd +++ /dev/null @@ -1,102 +0,0 @@ ---- -name: Mixed Subplots -permalink: r/mixed-subplots/ -description: How to create mixed subplots in R with Plotly. -layout: base -thumbnail: thumbnail/mixed_subplot.JPG -language: r -display_as: multiple_axes -order: 6 -output: - html_document: - keep_md: true ---- - -```{r, echo = FALSE, message=FALSE} -knitr::opts_chunk$set(message = FALSE, warning=FALSE) -``` -### Mixed Subplot - -```{r} -library(plotly) - -# read in Walmart data -df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/1962_2006_walmart_store_openings.csv") - - -# first plot - bar chart -total <- plyr::count(df$YEAR) -fit <- fitted(loess(total$freq ~ total$x)) - -fig2 <- plot_ly(data = total, x = ~x, y = ~freq, type = "bar", showlegend=FALSE, - marker=list(color=~x, showscale=FALSE)) -fig2 <- fig2 %>% add_lines(y = fit, showlegend=FALSE, color = 'black') -fig2 <- fig2 %>% layout(showlegend=FALSE, xaxis = list(side="right", showgrid=FALSE), - yaxis=list(showgrid=FALSE)) - - -# second plot - scattergeo map -g <- list( - scope = 'usa', - projection = list(type = 'albers usa'), - showlakes = TRUE, - lakecolor = toRGB('white')) - -fig3 <- plot_geo(df, lat = ~LAT, lon = ~LON) -fig3 <- fig3 %>% add_markers( - text = ~OPENDATE, showlegend=FALSE, - marker=list(color = ~YEAR, showscale=FALSE), - hoverinfo = "text") -fig3 <- fig3 %>% layout(geo = g, showlegend=FALSE) - - -# third plot - 3D mesh -#devtools::install_github("hypertidy/anglr") -library(anglr) -library(maptools) - -data(wrld_simpl) - -map1 <- subset(wrld_simpl, - NAME %in% c("Indonesia", "Papua New Guinea", "New Zealand", "Australia")) -## DEL model (like TRI in silicate) -delmesh <- anglr::globe(anglr::DEL(map1, max_area = 0.5)) -mesh <- as.mesh3d(delmesh) - - -# plot point cloud -x <- mesh$vb[1,] -y <- mesh$vb[2, ] -z <- mesh$vb[3,] -m <- matrix(c(x,y,z), ncol=3, dimnames=list(NULL,c("x","y","z"))) - -# colours in z don't make sense here, need to mafig object aesthetics above -zmean <- apply(t(mesh$it),MARGIN=1,function(row){mean(m[row,3])}) - -library(scales) -facecolor = colour_ramp( - brewer_pal(palette="RdBu")(9) -)(rescale(x=zmean)) - -fig1 <- plot_ly( - x = x, y = y, z = z, - i = mesh$it[1,]-1, j = mesh$it[2,]-1, k = mesh$it[3,]-1, - facecolor = facecolor, - type = "mesh3d" -) - - -# subplot -fig <- subplot(fig1, fig2, fig3, nrows = 2) -fig <- fig %>% layout(title = "Walmart Store Openings by Year", - xaxis = list(domain=list(x=c(0,0.5),y=c(0,0.5))), - scene = list(domain=list(x=c(0.5,1),y=c(0,0.5))), - xaxis2 = list(domain=list(x=c(0.5,1),y=c(0.5,1))), - showlegend=FALSE,showlegend2=FALSE) - -fig -``` - -#Reference - -See [https://plotly.com/r/reference](https://plotly.com/r/reference) for more information and options! diff --git a/r/2019-09-26-gauge-charts.Rmd b/r/2019-09-26-gauge-charts.Rmd index 24279fbf..6a7d3b80 100644 --- a/r/2019-09-26-gauge-charts.Rmd +++ b/r/2019-09-26-gauge-charts.Rmd @@ -22,7 +22,7 @@ knitr::opts_chunk$set(message = FALSE, warning=FALSE) The bar shows the target value, and the shading represents the progress toward that goal. Gauge charts, known as speedometer charts as well. This chart type is usually used to illustrate key business indicators. - The example below displays a basic gauge chart with default attributes. For more information about different added attributes check [indicator](https://plotly.com/r/indicator/) tutorial. + The example below displays a basic gauge chart with default attributes. ```{r} library(plotly) @@ -32,7 +32,7 @@ fig <- plot_ly( value = 270, title = list(text = "Speed"), type = "indicator", - mode = "gauge+number") + mode = "gauge+number") fig <- fig %>% layout(margin = list(l=20,r=30)) @@ -61,7 +61,7 @@ fig <- plot_ly( threshold = list( line = list(color = "red", width = 4), thickness = 0.75, - value = 490))) + value = 490))) fig <- fig %>% layout(margin = list(l=20,r=30)) @@ -92,7 +92,7 @@ fig <- plot_ly( threshold = list( line = list(color = "red", width = 4), thickness = 0.75, - value = 490))) + value = 490))) fig <- fig %>% layout( margin = list(l=20,r=30), diff --git a/r/2021-07-26-ml-roc-pr.Rmd b/r/2021-07-26-ml-roc-pr.Rmd index ab64be7e..65bf27de 100644 --- a/r/2021-07-26-ml-roc-pr.Rmd +++ b/r/2021-07-26-ml-roc-pr.Rmd @@ -65,55 +65,6 @@ fig2 <- fig2 %>% layout(legend=list(title=list(text=' Rate '))) fig2 ``` -## Basic binary ROC curve - -We display the area under the ROC curve (ROC AUC). While ROC shows how the TPR and FPR vary with the threshold, the ROC AUC is a measure of the classification model's ability to distinguish one class from the other. An ideal classifier will have ROC AUC = 1. In our example, we see that the ROC AUC is fairly high, thus consistent with our interpretation of the previous plots. - -```{r} -library(dplyr) -library(ggplot2) -library(plotly) -library(pROC) - -set.seed(0) -X <- matrix(rnorm(10000),nrow=500) -y <- sample(0:1, 500, replace=TRUE) -db <- data.frame(X,y) -db$y <- as.factor(db$y) -test_data = db[1:20] - -model<- logistic_reg() %>% - set_engine("glm") %>% - set_mode("classification") %>% - # Fit the model - fit(y ~., data = db) - - -ypred <- predict(model, - new_data = test_data, - type = "prob") - -yscore <- data.frame(ypred$.pred_0) -rdb <- cbind(db$y,yscore) -colnames(rdb) = c('y','yscore') - - -pdb <- roc_curve(rdb, y, yscore) -pdb$specificity <- 1 - pdb$specificity -auc = roc_auc(rdb, y, yscore) -auc = auc$.estimate - -tit = paste('ROC Curve (AUC = ',toString(round(auc,2)),')',sep = '') - - -fig <- plot_ly(data = pdb ,x = ~specificity, y = ~sensitivity, type = 'scatter', mode = 'lines', fill = 'tozeroy') %>% - layout(title = tit,xaxis = list(title = "False Positive Rate"), yaxis = list(title = "True Positive Rate")) %>% -add_segments(x = 0, xend = 1, y = 0, yend = 1, line = list(dash = "dash", color = 'black'),inherit = FALSE, showlegend = FALSE) -fig -``` - - - ## Multiclass ROC Curve When you have more than 2 classes, you will need to plot the ROC curve for each class separately. Make sure that you use a [one-versus-rest](https://cran.r-project.org/web/packages/multiclassPairs/vignettes/Tutorial.html) model, or make sure that your problem has a multi-label format; otherwise, your ROC curve might not return the expected results. @@ -189,52 +140,6 @@ fig ``` - -## Precision-Recall Curves - -Plotting the PR curve is very similar to plotting the ROC curve. The following examples are slightly modified from the previous examples: - -```{r} -library(dplyr) -library(ggplot2) -library(plotly) -library(pROC) - -set.seed(0) -X <- matrix(rnorm(10000),nrow=500) -y <- sample(0:1, 500, replace=TRUE) -db <- data.frame(X,y) -db$y <- as.factor(db$y) -test_data = db[1:20] - -model<- logistic_reg() %>% - set_engine("glm") %>% - set_mode("classification") %>% - # Fit the model - fit(y ~., data = db) - -ypred <- predict(model, - new_data = test_data, - type = "prob") - -yscore <- data.frame(ypred$.pred_0) -rdb <- cbind(db$y,yscore) -colnames(rdb) = c('y','yscore') - -pdb <- pr_curve(rdb, y, yscore) -auc = roc_auc(rdb, y, yscore) -auc = auc$.estimate - -tit = paste('ROC Curve (AUC = ',toString(round(auc,2)),')',sep = '') - - -fig <- plot_ly(data = pdb ,x = ~recall, y = ~precision, type = 'scatter', mode = 'lines', fill = 'tozeroy') %>% - add_segments(x = 0, xend = 1, y = 1, yend = 0, line = list(dash = "dash", color = 'black'),inherit = FALSE, showlegend = FALSE) %>% - layout(title = tit, xaxis = list(title = "Recall"), yaxis = list(title = "Precision") ) - -fig -``` - In this example, we use the average precision metric, which is an alternative scoring method to the area under the PR curve. ```{r} diff --git a/r/2021-08-03-horizontal-vertical-shapes.Rmd b/r/2021-08-03-horizontal-vertical-shapes.Rmd index 6c6abb13..e3c82145 100644 --- a/r/2021-08-03-horizontal-vertical-shapes.Rmd +++ b/r/2021-08-03-horizontal-vertical-shapes.Rmd @@ -141,7 +141,7 @@ After executing this code, give app$run_server() in the console to start the das ```{r} library(tidyquant) library(plotly) -tickers = c("GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT") +tickers = c("GOOG", "AAPL", "AMZN", "META", "NFLX", "MSFT") for (i in tickers){ getSymbols(i, from = "2018-01-01", @@ -149,13 +149,13 @@ getSymbols(i, stock <- data.frame(GOOG$GOOG.Adjusted, AAPL$AAPL.Adjusted, AMZN$AMZN.Adjusted, - FB$FB.Adjusted, + META$META.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$META.Adjusted <- stock$META.Adjusted/stock$META.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)) @@ -184,7 +184,7 @@ 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 = ~META, name = 'META')%>% 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"), @@ -200,7 +200,7 @@ 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") +tickers = c("GOOG", "AAPL", "AMZN", "META", "NFLX", "MSFT") for (i in tickers){ getSymbols(i, from = "2018-01-01", @@ -208,13 +208,13 @@ for (i in tickers){ stock <- data.frame(GOOG$GOOG.Adjusted, AAPL$AAPL.Adjusted, AMZN$AMZN.Adjusted, - FB$FB.Adjusted, + META$META.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$META.Adjusted <- stock$META.Adjusted/stock$META.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)) @@ -243,7 +243,7 @@ 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 = ~META, name = 'META')%>% add_trace(x = ~Dates, y = ~NFLX, name = 'NFLX')%>% add_trace(x = ~Dates, y = ~MSFT, name = 'MSFT')%>% layout(legend=list(title=list(text='company')), plot_bgcolor = "#e5ecf6", shapes = list(list(type = "rect", text = 'decline', fillcolor = "green", line = list(color = "green"), @@ -262,7 +262,7 @@ The same line or box is added to multiple plots, and these plots are finally add ```{r} library(tidyquant) library(plotly) -tickers = c("GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT") +tickers = c("GOOG", "AAPL", "AMZN", "META", "NFLX", "MSFT") for (i in tickers){ getSymbols(i, from = "2018-01-01", @@ -289,13 +289,13 @@ y <- list( stock <- data.frame(GOOG$GOOG.Adjusted, AAPL$AAPL.Adjusted, AMZN$AMZN.Adjusted, - FB$FB.Adjusted, + META$META.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$META.Adjusted <- stock$META.Adjusted/stock$META.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)) @@ -329,7 +329,7 @@ fig3 <- plot_ly(stock, type = 'scatter', mode = 'lines')%>% text = c("decline")) fig4 <- plot_ly(stock, type = 'scatter', mode = 'lines')%>% - add_trace(x = ~Dates, y = ~FB, name = 'FB')%>% + add_trace(x = ~Dates, y = ~META, name = 'META')%>% 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')%>% @@ -384,7 +384,7 @@ annotations = list( x = 0.775, y = 0.666, font = list(size = 10), - text = "company=FB", + text = "company=META", xref = "paper", yref = "paper", xanchor = "center", diff --git a/r/2021-08-18-discrete-colors.Rmd b/r/2021-08-18-discrete-colors.Rmd index a2d33a9f..556b4df5 100644 --- a/r/2021-08-18-discrete-colors.Rmd +++ b/r/2021-08-18-discrete-colors.Rmd @@ -43,14 +43,14 @@ data("tips") fig <- plot_ly(tips, x = ~total_bill, y = ~tip, split = ~smoker, type = 'scatter', mode = 'markers') %>% layout(legend=list(title=list(text='smoker')), title = "String 'smoker' values mean discrete colors", - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff') ) fig ``` @@ -65,14 +65,14 @@ data("tips") fig <- plot_ly(tips, x = ~total_bill, y = ~tip, color = ~size, type = 'scatter', mode = 'markers') %>% layout(title = "Numeric 'size' values mean continuous color", - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff') ) fig ``` @@ -89,101 +89,76 @@ tips$size = as.character(tips$size) #convert to string fig <- plot_ly(tips, x = ~total_bill, y = ~tip, split = ~size, type = 'scatter', mode = 'markers') %>% layout(title = "String 'size' values mean discrete colors", - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff') ) fig ``` -Converting a string column to a numeric one is also quite straightforward: - -```{r} - -library(plotly) -library(rWind) -data(wind) - -fig <- plot_ly(wind, r = ~r, theta = ~t, type="barpolar", color = ~nms, - marker =list(colorscale = 'Accent')) %>% - layout(title = 'Part of a continuous color scale used as a discrete sequence', legend=list(title=list(text='strength')), - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff') , polar = list(angularaxis = list( - rotation = 90, - direction = 'clockwise' - )), margin = 0.01) -fig - ``` ### Discrete Colors 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. - +[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 eval=FALSE} -library(dash) -library(dashCoreComponents) -library(dashHtmlComponents) -library(plotly) - -app <- Dash$new() - -app$layout( - htmlDiv( - list( - dccGraph(id = 'graph'), - htmlLabel("Color mode:"), - dccRadioItems( - id='radio', - options = list(list(label = "discrete", value = "d"), - list(label = "continuous", value = "c")), - value = 'Secondary' - ) - ) - ) -) -app$callback( - output(id = 'graph', property='figure'), - params=list(input(id='radio', property='value')), - function(value) { - if(value == 'd'){ +library(dash) +library(dashCoreComponents) +library(dashHtmlComponents) +library(plotly) + +app <- Dash$new() + +app$layout( + htmlDiv( + list( + dccGraph(id = 'graph'), + htmlLabel("Color mode:"), + dccRadioItems( + id='radio', + options = list(list(label = "discrete", value = "d"), + list(label = "continuous", value = "c")), + value = 'Secondary' + ) + ) + ) +) +app$callback( + output(id = 'graph', property='figure'), + params=list(input(id='radio', property='value')), + function(value) { + if(value == 'd'){ library(plotly) library(reshape) data("tips") - + fig <- plot_ly(tips, x = ~total_bill, y = ~tip, split = ~size, type = 'scatter', mode = 'markers') %>% layout(title = "'size' values mean discrete colors") - - return(fig) - } - else{ + + return(fig) + } + else{ library(plotly) library(reshape) data("tips") - + fig <- plot_ly(tips, x = ~total_bill, y = ~tip, color = ~size, type = 'scatter', mode = 'markers') %>% layout(title = "'size' values mean continuous color") - - return(fig) - } - }) + + return(fig) + } + }) ``` Use `app$run_server()` to run the dash app. @@ -192,12 +167,10 @@ Use `app$run_server()` to run the dash app. By default, Plotly will use the color sequence from the `colors` attribute, and the default active template is `plotly` which uses the `plotly` color sequence. You can choose any of the following built-in qualitative color sequences however, or define your own. -```{r} +```{r eval=FALSE} library("RColorBrewer") display.brewer.all(type = 'qual') - - ``` @@ -212,14 +185,14 @@ data("gapminder") fig <- plot_ly(gapminder, x = ~year, y = ~lifeExp, type = 'scatter', mode = 'lines', color = ~continent, line =list(colorscale = 'Accent')) %>% layout(title = 'Built-in Accent color sequence', legend=list(title=list(text='continent')), - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff') ) fig @@ -231,29 +204,29 @@ The Plotly`colors` argument accepts explicitly-constructed color sequences as we ```{r} -library(plotly) -library(gapminder) -data("gapminder") +library(plotly) +library(gapminder) +data("gapminder") -data <- gapminder[gapminder$year == 2007, ] +data <- gapminder[gapminder$year == 2007, ] -fig <- plot_ly()%>% +fig <- plot_ly()%>% add_bars(data = data, x = ~pop, y = ~continent, width = 1, color = ~continent, orientation = 'h', text = ~ country, - hovertemplate = paste('%{text}', - '
Continent: %{y}
', - 'pop: $%{x}'), - colors = c("red", "green", "blue", "goldenrod", "magenta") + hovertemplate = paste('%{text}', + '
Continent: %{y}
', + 'pop: $%{x}'), + colors = c("red", "green", "blue", "goldenrod", "magenta") ) %>% layout( title = "Explicit color sequence", legend=list(title=list(text='continent')), - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff')) fig @@ -270,14 +243,14 @@ fig <- plot_ly(tips, x = ~total_bill, y = ~tip, type = 'scatter', mode = 'marker colors = c("red", "blue")) fig <- fig %>% layout( title = "Ambiguous! given colors mapped to some values only", legend=list(title=list(text='day')), - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff')) fig @@ -297,22 +270,22 @@ pal <- c("red", "green", "blue", "goldenrod", "magenta") pal <- setNames(pal, c("Europe", "Asia", "Americas", "Oceania", "Africa")) -fig <- plot_ly()%>% - add_bars(data = data, x = ~pop, y = ~continent, width = 1, color = ~continent, orientation = 'h', +fig <- plot_ly()%>% + add_bars(data = data, x = ~pop, y = ~continent, width = 1, color = ~continent, orientation = 'h', text = ~ country, - hovertemplate = paste('%{text}', - '
Continent: %{y}
', - 'pop: $%{x}'), + hovertemplate = paste('%{text}', + '
Continent: %{y}
', + 'pop: $%{x}'), colors = pal) %>% layout( title = "Explicit color mapping", legend=list(title=list(text='continent')), - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff')) fig @@ -324,24 +297,24 @@ If your data set already contains valid CSS colors which you wish to use directl ```{r} -library(plotly) -library(gapminder) -data(gapminder) -fig <- plot_ly(x = c("a","b","c"), y = c(1,3,2), type = 'bar', - marker = list(color = c('red', 'goldenrod', - '#00D'))) -fig <- fig %>% layout(plot_bgcolor='#e5ecf6', - xaxis = list( - title = 'x', - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( - title = 'y', - zerolinecolor = '#ffff', - zerolinewidth = 2, +library(plotly) +library(gapminder) +data(gapminder) +fig <- plot_ly(x = c("a","b","c"), y = c(1,3,2), type = 'bar', + marker = list(color = c('red', 'goldenrod', + '#00D'))) +fig <- fig %>% layout(plot_bgcolor='#e5ecf6', + xaxis = list( + title = 'x', + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( + title = 'y', + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff' - )) + )) fig ``` @@ -355,30 +328,30 @@ library(plotly) library(gapminder) data("gapminder") -data <- gapminder[gapminder$year == 2007, ] +data <- gapminder[gapminder$year == 2007, ] pal <- c("green", "blue", "magenta", "red", "goldenrod") pal <- setNames(pal, c("Europe", "Asia", "Americas", "Oceania", "Africa")) -fig <- plot_ly()%>% - add_bars(data = data, x = ~pop, y = ~continent, width = 1, color = ~continent, orientation = 'h', +fig <- plot_ly()%>% + add_bars(data = data, x = ~pop, y = ~continent, width = 1, color = ~continent, orientation = 'h', text = ~ country, - hovertemplate = paste('%{text}', - '
Continent: %{y}
', - 'pop: $%{x}'), + hovertemplate = paste('%{text}', + '
Continent: %{y}
', + 'pop: $%{x}'), colors = pal) %>% layout( title = "Explicit color sequence with explicit ordering", legend=list(title=list(text='continent')), - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( categoryorder = "array", categoryarray = c("Asia","Oceania", "Europe", "Africa", "Americas"), - zerolinecolor = '#ffff', - zerolinewidth = 2, + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff'), bargap = 1) @@ -392,30 +365,30 @@ library(plotly) library(gapminder) data("gapminder") -data <- gapminder[gapminder$year == 2007, ] +data <- gapminder[gapminder$year == 2007, ] pal <- c("red", "green", "blue", "goldenrod", "magenta") pal <- setNames(pal, c("Europe", "Asia", "Americas", "Oceania", "Africa")) -fig <- plot_ly()%>% - add_bars(data = data, x = ~pop, y = ~continent, width = 1, color = ~continent, orientation = 'h', +fig <- plot_ly()%>% + add_bars(data = data, x = ~pop, y = ~continent, width = 1, color = ~continent, orientation = 'h', text = ~ country, - hovertemplate = paste('%{text}', - '
Continent: %{y}
', - 'pop: $%{x}'), + hovertemplate = paste('%{text}', + '
Continent: %{y}
', + 'pop: $%{x}'), colors = pal) %>% layout( title = "Explicit color mapping with explicit ordering", legend=list(title=list(text='continent')), - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - yaxis = list( + plot_bgcolor='#e5ecf6', + xaxis = list( + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + yaxis = list( categoryorder = "array", categoryarray = c("Asia","Oceania", "Europe", "Africa", "Americas"), - zerolinecolor = '#ffff', - zerolinewidth = 2, + zerolinecolor = '#ffff', + zerolinewidth = 2, gridcolor = 'ffff'), bargap = 1) @@ -423,31 +396,3 @@ fig ``` -### Using Sequential Scales as Discrete Sequences - -In most cases, discrete/qualitative/categorical data values have no meaningful natural ordering, such as in the continents example used above. In some cases, however, there is a meaningful order, and in this case it can be helpful and appealing to use part of a continuous scale as a discrete sequence, as in the following wind rose chart: - -```{r} -library(plotly) -library(rWind) -data(wind) - -fig <- plot_ly(wind, r = ~r, theta = ~t, type="barpolar", color = ~nms, - marker =list(colorscale = 'Accent')) %>% - layout(title = list(text='Part of a continuous color scale used as a discrete sequence' - ,font =list(size = 15)), legend=list(title=list(text='strength')), - plot_bgcolor='#e5ecf6', - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - xaxis = list( - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff') , polar = list(angularaxis = list( - rotation = 90, - direction = 'clockwise' - )), margin = 0.01) -fig - -``` diff --git a/r/2021-08-21-map-configuration.Rmd b/r/2021-08-21-map-configuration.Rmd index 6c33337e..b3e1e09c 100644 --- a/r/2021-08-21-map-configuration.Rmd +++ b/r/2021-08-21-map-configuration.Rmd @@ -69,7 +69,7 @@ fig ### Disabling Base Maps -In certain cases, such as large scale [choropleth maps](plotly.com/r/choropleth-maps/), the default physical map can be distracting. In this case the `layout$geo$visible` attribute can be set to `FALSE` to hide all base map attributes except those which are explicitly set to true. For example in the following map we hide all physical features except rivers and lakes, neither of which are shown by default: +In certain cases, such as large scale [choropleth maps](https://plotly.com/r/choropleth-maps/), the default physical map can be distracting. In this case the `layout$geo$visible` attribute can be set to `FALSE` to hide all base map attributes except those which are explicitly set to true. For example in the following map we hide all physical features except rivers and lakes, neither of which are shown by default: ```{r} library(plotly) @@ -97,7 +97,7 @@ In addition to physical base map features, a "cultural" base map is included whi > Natural Earth Vector draws boundaries of countries according to defacto status. We show who actually controls the situation on the ground. -**To create a map with your own cultural features** please refer to our [choropleth documentation](plotly.com/r/choropleth-maps/). +**To create a map with your own cultural features** please refer to our [choropleth documentation](https://plotly.com/r/choropleth-maps/). Here is a map with only cultural features enabled and styled, at a 1:50m resolution, which includes only country boundaries. See below for country sub-unit cultural base map features: diff --git a/r/2021-08-26-time-series.Rmd b/r/2021-08-26-time-series.Rmd index 2452b4f6..3944a7aa 100644 --- a/r/2021-08-26-time-series.Rmd +++ b/r/2021-08-26-time-series.Rmd @@ -127,7 +127,7 @@ Or this facetted area plot: ```{r} library(tidyquant) library(plotly) -tickers = c("GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT") +tickers = c("GOOG", "AAPL", "AMZN", "META", "NFLX", "MSFT") for (i in tickers){ getSymbols(i, from = "2018-01-01", @@ -143,13 +143,13 @@ y <- list( stock <- data.frame(GOOG$GOOG.Adjusted, AAPL$AAPL.Adjusted, AMZN$AMZN.Adjusted, - FB$FB.Adjusted, + META$META.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$META.Adjusted <- stock$META.Adjusted/stock$META.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)) @@ -178,7 +178,7 @@ fig3 <- plot_ly(stock, type = 'scatter', mode = 'lines', fill = 'tonexty')%>% fig4 <- plot_ly(stock, type = 'scatter', mode = 'lines', fill = 'tonexty')%>% - add_trace(x = ~Dates, y = ~FB, name = 'FB')%>% + add_trace(x = ~Dates, y = ~META, name = 'META')%>% layout(legend=list(title=list(text='company')), xaxis = ax, yaxis = list(range = c(0.5,2),title = '', showticklabels = FALSE)) @@ -239,7 +239,7 @@ annotations = list( x = 0.775, y = 0.64, font = list(size = 10), - text = "company=FB", + text = "company=META", xref = "paper", yref = "paper", xanchor = "center", @@ -285,7 +285,7 @@ Note that by default, the formatting of values of X and Y values in the hover la ```{r} library(tidyquant) library(plotly) -tickers = c("GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT") +tickers = c("GOOG", "AAPL", "AMZN", "META", "NFLX", "MSFT") for (i in tickers){ getSymbols(i, from = "2018-01-01", @@ -293,13 +293,13 @@ for (i in tickers){ stock <- data.frame(GOOG$GOOG.Adjusted, AAPL$AAPL.Adjusted, AMZN$AMZN.Adjusted, - FB$FB.Adjusted, + META$META.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$META.Adjusted <- stock$META.Adjusted/stock$META.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)) @@ -309,7 +309,7 @@ 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 = ~META, name = 'META')%>% add_trace(x = ~Dates, y = ~NFLX, name = 'NFLX')%>% add_trace(x = ~Dates, y = ~MSFT, name = 'MSFT')%>% layout(title = 'custom tick labels',legend=list(title=list(text='variable')), @@ -338,7 +338,7 @@ By setting the `ticklabelmode` attribute to `"period"` (the default is `"instant ```{r} library(tidyquant) library(plotly) -tickers = c("GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT") +tickers = c("GOOG", "AAPL", "AMZN", "META", "NFLX", "MSFT") for (i in tickers){ getSymbols(i, from = "2018-01-01", @@ -346,13 +346,13 @@ for (i in tickers){ stock <- data.frame(GOOG$GOOG.Adjusted, AAPL$AAPL.Adjusted, AMZN$AMZN.Adjusted, - FB$FB.Adjusted, + META$META.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$META.Adjusted <- stock$META.Adjusted/stock$META.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)) @@ -362,7 +362,7 @@ 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 = ~META, name = 'META')%>% add_trace(x = ~Dates, y = ~NFLX, name = 'NFLX')%>% add_trace(x = ~Dates, y = ~MSFT, name = 'MSFT')%>% layout(title = 'custom tick labels with ticklabelmode="period"',legend=list(title=list(text='variable')),