From 29523d39fa823226f243d9221867ec1cdd0a8186 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Mon, 27 May 2024 13:21:58 -0400 Subject: [PATCH 01/30] fix links --- r/2015-07-30-text-and-annotations.Rmd | 10 +++++----- r/2019-09-26-gauge-charts.Rmd | 8 ++++---- r/2021-08-21-map-configuration.Rmd | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) 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/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-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: From 07479b30e6513b13fd35eef615492093ce22f5b3 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Mon, 27 May 2024 16:21:32 -0400 Subject: [PATCH 02/30] remove examples that no longer run --- DESCRIPTION | 3 +- r/2016-06-17-3d-tri-surf.Rmd | 41 ------------- r/2017-01-13-mixed-subplot.Rmd | 102 --------------------------------- 3 files changed, 1 insertion(+), 145 deletions(-) delete mode 100644 r/2017-01-13-mixed-subplot.Rmd 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/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! From 9df3a215222d74486edfdc3d05bdbb33e2bfcb8a Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Mon, 27 May 2024 16:57:21 -0400 Subject: [PATCH 03/30] Update 2021-08-04-legend.Rmd --- ggplot2/2021-08-04-legend.Rmd | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) 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()) From a27be6274bce1325fd648d124a20217d99fbe41d Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Mon, 27 May 2024 16:58:58 -0400 Subject: [PATCH 04/30] Update 2021-08-04-log-plot.Rmd --- ggplot2/2021-08-04-log-plot.Rmd | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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() From 753444e966edcd343bdc794d94ac9a32163743fc Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Mon, 27 May 2024 17:01:49 -0400 Subject: [PATCH 05/30] Update 2021-08-04-strip-charts.Rmd --- ggplot2/2021-08-04-strip-charts.Rmd | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/ggplot2/2021-08-04-strip-charts.Rmd b/ggplot2/2021-08-04-strip-charts.Rmd index 3bce6933..8a307ebc 100644 --- a/ggplot2/2021-08-04-strip-charts.Rmd +++ b/ggplot2/2021-08-04-strip-charts.Rmd @@ -26,10 +26,10 @@ library(ggplot2) ToothGrowth$dose <- as.factor(ToothGrowth$dose) -ggplot(ToothGrowth, aes(x=dose, y=len)) + +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 +48,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 +65,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 +83,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 +99,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 +114,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 +122,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 +153,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) ``` From 0d13036ceef1f58530048d6960b61236c70ac2f8 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Mon, 27 May 2024 17:10:13 -0400 Subject: [PATCH 06/30] Update DESCRIPTION --- DESCRIPTION | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 96dd5447..1d589d70 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -72,4 +72,5 @@ Imports: fmsb, plotROC, tidyquant, - ggplot2movies + ggplot2movies, + pROC From f734bfcfbf590e41ae46b9c0e236004f063ec86e Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Mon, 27 May 2024 17:29:55 -0400 Subject: [PATCH 07/30] fix stock name --- r/2021-08-03-horizontal-vertical-shapes.Rmd | 26 ++++++++++----------- 1 file changed, 13 insertions(+), 13 deletions(-) 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", From 5e53a75d43bf2def06e842fe92d9561e645b2dd8 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Mon, 27 May 2024 19:29:01 -0400 Subject: [PATCH 08/30] Update DESCRIPTION --- DESCRIPTION | 1 + 1 file changed, 1 insertion(+) diff --git a/DESCRIPTION b/DESCRIPTION index 1d589d70..0960ff7b 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -74,3 +74,4 @@ Imports: tidyquant, ggplot2movies, pROC + rWind From 1338f6933747274ba8c46fd18effb1b1170b593e Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 09:48:40 -0400 Subject: [PATCH 09/30] Delete 2021-07-26-ml-roc-pr.Rmd --- r/2021-07-26-ml-roc-pr.Rmd | 315 ------------------------------------- 1 file changed, 315 deletions(-) delete mode 100644 r/2021-07-26-ml-roc-pr.Rmd diff --git a/r/2021-07-26-ml-roc-pr.Rmd b/r/2021-07-26-ml-roc-pr.Rmd deleted file mode 100644 index ab64be7e..00000000 --- a/r/2021-07-26-ml-roc-pr.Rmd +++ /dev/null @@ -1,315 +0,0 @@ ---- -description: Interpret the results of your classification using Receiver Operating Characteristics (ROC) and Precision-Recall (PR) Curves in R with Plotly. -display_as: ai_ml -language: r -layout: base -name: ROC and PR Curves -order: 3 -output: - html_document: - keep_md: true -permalink: r/roc-and-pr-curves/ -thumbnail: thumbnail/ml-roc-pr.png ---- - -```{r, echo = FALSE, message=FALSE} -knitr::opts_chunk$set(message = FALSE, warning = FALSE) -``` -## ROC and PR Curves in R - -Interpret the results of your classification using Receiver Operating Characteristics (ROC) and Precision-Recall (PR) Curves in R with Plotly. - -## Preliminary plots - -Before diving into the receiver operating characteristic (ROC) curve, we will look at two plots that will give some context to the thresholds mechanism behind the ROC and PR curves. - -In the histogram, we observe that the score spread such that most of the positive labels are binned near 1, and a lot of the negative labels are close to 0. When we set a threshold on the score, all of the bins to its left will be classified as 0's, and everything to the right will be 1's. There are obviously a few outliers, such as **negative** samples that our model gave a high score, and *positive* samples with a low score. If we set a threshold right in the middle, those outliers will respectively become **false positives** and *false negatives*. - -As we adjust thresholds, the number of false positives will increase or decrease, and at the same time the number of true positives will also change; this is shown in the second plot. As you can see, the model seems to perform fairly well, because the true positive rate and the false positive rate decreases sharply as we increase the threshold. Those two lines each represent a dimension of the ROC curve. - - -```{r} -library(plotly) -library(tidymodels) -set.seed(0) -X <- matrix(rnorm(10000),nrow=500) -y <- sample(0:1, 500, replace=TRUE) -data <- data.frame(X,y) -data$y <- as.factor(data$y) -X <- subset(data,select = -c(y)) -logistic_glm <- - logistic_reg() %>% - set_engine("glm") %>% - set_mode("classification") %>% - fit(y ~ ., data = data) - -y_scores <- logistic_glm %>% - predict(X, type = 'prob') - -y_score <- y_scores$.pred_1 -db <- data.frame(data$y, y_score) - -z <- roc_curve(data = db, 'data.y', 'y_score') -z$specificity <- 1 - z$specificity -colnames(z) <- c('threshold', 'tpr', 'fpr') - -fig1 <- plot_ly(x= y_score, color = data$y, colors = c('blue', 'red'), type = 'histogram', alpha = 0.5, nbinsx = 50) %>% - layout(barmode = "overlay") -fig1 - -fig2 <- plot_ly(data = z, x = ~threshold) %>% - add_trace(y = ~fpr, mode = 'lines', name = 'False Positive Rate', type = 'scatter')%>% - add_trace(y = ~tpr, mode = 'lines', name = 'True Positive Rate', type = 'scatter')%>% - layout(title = 'TPR and FPR at every threshold') -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. - -```{r} -library(plotly) -library(tidymodels) -library(fastDummies) - -# Artificially add noise to make task harder -data(iris) -ind <- sample.int(150, 50) -samples <- sample(x = iris$Species, size = 50) -iris[ind,'Species'] = samples - -# Define the inputs and outputs -X <- subset(iris, select = -c(Species)) -iris$Species <- as.factor(iris$Species) - -# Fit the model -logistic <- - multinom_reg() %>% - set_engine("nnet") %>% - set_mode("classification") %>% - fit(Species ~ ., data = iris) - -y_scores <- logistic %>% - predict(X, type = 'prob') - -# One hot encode the labels in order to plot them -y_onehot <- dummy_cols(iris$Species) -colnames(y_onehot) <- c('drop', 'setosa', 'versicolor', 'virginica') -y_onehot <- subset(y_onehot, select = -c(drop)) - -z = cbind(y_scores, y_onehot) - -z$setosa <- as.factor(z$setosa) -roc_setosa <- roc_curve(data = z, setosa, .pred_setosa) -roc_setosa$specificity <- 1 - roc_setosa$specificity -colnames(roc_setosa) <- c('threshold', 'tpr', 'fpr') -auc_setosa <- roc_auc(data = z, setosa, .pred_setosa) -auc_setosa <- auc_setosa$.estimate -setosa <- paste('setosa (AUC=',toString(round(1-auc_setosa,2)),')',sep = '') - -z$versicolor <- as.factor(z$versicolor) -roc_versicolor <- roc_curve(data = z, versicolor, .pred_versicolor) -roc_versicolor$specificity <- 1 - roc_versicolor$specificity -colnames(roc_versicolor) <- c('threshold', 'tpr', 'fpr') -auc_versicolor <- roc_auc(data = z, versicolor, .pred_versicolor) -auc_versicolor <- auc_versicolor$.estimate -versicolor <- paste('versicolor (AUC=',toString(round(1-auc_versicolor,2)),')', sep = '') - -z$virginica <- as.factor(z$virginica) -roc_virginica <- roc_curve(data = z, virginica, .pred_virginica) -roc_virginica$specificity <- 1 - roc_virginica$specificity -colnames(roc_virginica) <- c('threshold', 'tpr', 'fpr') -auc_virginica <- roc_auc(data = z, virginica, .pred_virginica) -auc_virginica <- auc_virginica$.estimate -virginica <- paste('virginica (AUC=',toString(round(1-auc_virginica,2)),')',sep = '') - -# Create an empty figure, and iteratively add a line for each class -fig <- plot_ly()%>% - add_segments(x = 0, xend = 1, y = 0, yend = 1, line = list(dash = "dash", color = 'black'), showlegend = FALSE) %>% - add_trace(data = roc_setosa,x = ~fpr, y = ~tpr, mode = 'lines', name = setosa, type = 'scatter')%>% - add_trace(data = roc_versicolor,x = ~fpr, y = ~tpr, mode = 'lines', name = versicolor, type = 'scatter')%>% - add_trace(data = roc_virginica,x = ~fpr, y = ~tpr, mode = 'lines', name = virginica, type = 'scatter')%>% - layout(xaxis = list( - title = "False Positive Rate" - ), yaxis = list( - title = "True Positive Rate" - ),legend = list(x = 100, y = 0.5)) -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} -library(plotly) -library(tidymodels) -library(fastDummies) - -# Artificially add noise to make task harder -data(iris) -ind <- sample.int(150, 50) -samples <- sample(x = iris$Species, size = 50) -iris[ind,'Species'] = samples - -# Define the inputs and outputs -X <- subset(iris, select = -c(Species)) -iris$Species <- as.factor(iris$Species) - -# Fit the model -logistic <- - multinom_reg() %>% - set_engine("nnet") %>% - set_mode("classification") %>% - fit(Species ~ ., data = iris) - -y_scores <- logistic %>% - predict(X, type = 'prob') - -y_onehot <- dummy_cols(iris$Species) -colnames(y_onehot) <- c('drop', 'setosa', 'versicolor', 'virginica') -y_onehot <- subset(y_onehot, select = -c(drop)) - -z = cbind(y_scores, y_onehot) - -z$setosa <- as.factor(z$setosa) -pr_setosa <- pr_curve(data = z, setosa, .pred_setosa) -aps_setosa <- mean(pr_setosa$precision) -setosa <- paste('setosa (AP =',toString(round(aps_setosa,2)),')',sep = '') - - -z$versicolor <- as.factor(z$versicolor) -pr_versicolor <- pr_curve(data = z, versicolor, .pred_versicolor) -aps_versicolor <- mean(pr_versicolor$precision) -versicolor <- paste('versicolor (AP = ',toString(round(aps_versicolor,2)),')',sep = '') - -z$virginica <- as.factor(z$virginica) -pr_virginica <- pr_curve(data = z, virginica, .pred_virginica) -aps_virginica <- mean(pr_virginica$precision) -virginica <- paste('virginica (AP = ',toString(round(aps_virginica,2)),')',sep = '') - -# Create an empty figure, and add a new line for each class -fig <- plot_ly()%>% - add_segments(x = 0, xend = 1, y = 1, yend = 0, line = list(dash = "dash", color = 'black'), showlegend = FALSE) %>% - add_trace(data = pr_setosa,x = ~recall, y = ~precision, mode = 'lines', name = setosa, type = 'scatter')%>% - add_trace(data = pr_versicolor,x = ~recall, y = ~precision, mode = 'lines', name = versicolor, type = 'scatter')%>% - add_trace(data = pr_virginica,x = ~recall, y = ~precision, mode = 'lines', name = virginica, type = 'scatter')%>% - layout(xaxis = list( - title = "Recall" - ), yaxis = list( - title = "Precision" - ),legend = list(x = 100, y = 0.5)) -fig -``` - - -## References - - -Learn more about histograms, filled area plots and line charts: - -* https://plot.ly/r/histograms/ - -* https://plot.ly/r/filled-area-plots/ - -* https://plot.ly/r/line-charts/ - - - - From 67b2c4378f7cd69325da2241636300ed1070a134 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 10:41:26 -0400 Subject: [PATCH 10/30] specify tidyverse image --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index d39569df..1a4b9765 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,7 +3,7 @@ jobs: build: working_directory: ~/project docker: - - image: rocker/tidyverse + - image: rocker/tidyverse:3.6.3 steps: - add_ssh_keys: fingerprints: From 93368b2ebcafe55d8b136a563e03b47e3ecfd0f2 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 10:41:35 -0400 Subject: [PATCH 11/30] revert adding depdenencies --- DESCRIPTION | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 0960ff7b..96dd5447 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -72,6 +72,4 @@ Imports: fmsb, plotROC, tidyquant, - ggplot2movies, - pROC - rWind + ggplot2movies From 97c788429e19a7c3b6ac49f0cd479627aa7cc6d6 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 10:44:04 -0400 Subject: [PATCH 12/30] Update config.yml --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 1a4b9765..fcf11f64 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,7 +3,7 @@ jobs: build: working_directory: ~/project docker: - - image: rocker/tidyverse:3.6.3 + - image: rocker/tidyverse:3 steps: - add_ssh_keys: fingerprints: From 092d803f174a84994f2482b7f413d762bb685b22 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 10:46:56 -0400 Subject: [PATCH 13/30] Update config.yml --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index fcf11f64..d39569df 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,7 +3,7 @@ jobs: build: working_directory: ~/project docker: - - image: rocker/tidyverse:3 + - image: rocker/tidyverse steps: - add_ssh_keys: fingerprints: From 797d9cfa93f813bd6b4350ce4895f2add498b0da Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 10:52:27 -0400 Subject: [PATCH 14/30] Delete 2021-08-18-discrete-colors.Rmd --- r/2021-08-18-discrete-colors.Rmd | 453 ------------------------------- 1 file changed, 453 deletions(-) delete mode 100644 r/2021-08-18-discrete-colors.Rmd diff --git a/r/2021-08-18-discrete-colors.Rmd b/r/2021-08-18-discrete-colors.Rmd deleted file mode 100644 index a2d33a9f..00000000 --- a/r/2021-08-18-discrete-colors.Rmd +++ /dev/null @@ -1,453 +0,0 @@ ---- -description: How to use and configure discrete color sequences, also known as - categorical or qualitative color scales in R. -display_as: file_settings -has_thumbnail: true -language: r -layout: base -name: Discrete Colors -order: 21 -output: - html_document: - keep_md: true -permalink: r/discrete-color/ -thumbnail: thumbnail/heatmap_colorscale.jpg ---- - -```{r, echo = FALSE, message=FALSE} -knitr::opts_chunk$set(message = FALSE, warning = FALSE) -``` - -### Discrete vs Continuous Color - -In the same way as the X or Y position of a mark in cartesian coordinates can be used to represent continuous values (i.e. amounts or moments in time) or categories (i.e. labels), color can be used to represent continuous or discrete data. This page is about using color to represent **categorical** data using discrete colors, but Plotly can also [represent continuous values with color](https://plotly.com/r/colorscales/). - -### Discrete Color Concepts - -This document explains the following discrete-color-related concepts: - -- **color sequences** are lists of colors to be mapped onto discrete data values. No interpolation occurs when using color sequences, unlike with [continuous color scales](https://plotly.com/r/colorscales/), and each color is used as-is. Color sequence defaults depend on the `colors` attribute and can be explicitly specified using a vector of colors as argument. -- **legends** are visible representations of the mapping between colors and data values. Legend markers also change shape when used with various kinds of traces, such as symbols or lines for scatter-like traces. [Legends are configurable](https://plotly.com/r/legend/) under the `layout.legend` attribute. Legends are the discrete equivalent of [continuous color bars](https://plotly.com/r/colorscales/) - -### Discrete Color with Plotly - -Most Plotly functions accept a `color` argument which automatically assigns data values to discrete colors **if the data is non-numeric**. If the data is numeric, the color will automatically be considered [continuous](https://plotly.com/r/colorscales/). This means that numeric strings must be parsed to be used for continuous color, and conversely, numbers used as category codes must be converted to strings. - -For example, in the `tips` dataset, the `smoker` column contains strings: - -```{r} - -library(plotly) -library(reshape) -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, - gridcolor = 'ffff') ) -fig -``` - -The `size` column, however, contains numbers: - -```{r} - -library(plotly) -library(reshape) -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, - gridcolor = 'ffff') ) -fig -``` - -Converting this column to strings is very straightforward, but note that the ordering in the legend may not be sequential by default, but here it produces sequentially (see below for how to control discrete order): - -```{r} - -library(plotly) -library(reshape) -data("tips") - -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, - 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. - -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(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{ - 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) - } - }) -``` - -Use `app$run_server()` to run the dash app. - -### Color Sequences in Plotly - -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} - -library("RColorBrewer") -display.brewer.all(type = 'qual') - - -``` - - -Here is an example that creates a scatter plot using Plotly , with points colored using the built-in qualitative `accent` color sequence. - -```{r} - -library(plotly) -library(gapminder) -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, - gridcolor = 'ffff') ) -fig - -``` - -### Explicitly Constructing a Color Sequence - -The Plotly`colors` argument accepts explicitly-constructed color sequences as well, as lists of CSS colors: - -```{r} - -library(plotly) -library(gapminder) -data("gapminder") - -data <- gapminder[gapminder$year == 2007, ] - - -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") - ) %>% - 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, - gridcolor = 'ffff')) - -fig -``` - -**_Warning_**: If your color sequence has fewer colors than the number of unique values in the column you are mapping to `color`, the given colors will be mapped for some values and random colors will be mapped for other values : - -```{r} - -library(plotly) -data("tips") - -fig <- plot_ly(tips, x = ~total_bill, y = ~tip, type = 'scatter', mode = 'markers', color = ~day, - 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, - gridcolor = 'ffff')) - -fig -``` - -### Directly Mapping Colors to Data Values - -The example above assigned colors to data values on a first-come-first-served basis, but you can directly map colors to data values if this is important to your application with `colors`. Note that this does not change the order in which values appear in the figure or legend, as can be controlled below: - -```{r} - -library(plotly) -library(gapminder) -data("gapminder") - -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', - text = ~ country, - 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, - gridcolor = 'ffff')) - -fig - - -``` - -If your data set already contains valid CSS colors which you wish to use directly, you can pass the special value `"identity"` to `colors`, in which case the legend is hidden by default, and the color does not appear in the hover label: - -```{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, - gridcolor = 'ffff' - )) - -fig -``` - -### Controlling Discrete Color Order - -Plotly lets you specify an ordering over categorical variables with `categoryorder`, which will apply to colors and legends as well as symbols and [axes](https://plotly.com/r/axes/). This can be used with either `colors` or `color`. - -```{r} -library(plotly) -library(gapminder) -data("gapminder") - -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', - text = ~ country, - 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( - categoryorder = "array", - categoryarray = c("Asia","Oceania", "Europe", "Africa", "Americas"), - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - bargap = 1) - -fig - -``` - -```{r} - -library(plotly) -library(gapminder) -data("gapminder") - -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', - text = ~ country, - 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( - categoryorder = "array", - categoryarray = c("Asia","Oceania", "Europe", "Africa", "Americas"), - zerolinecolor = '#ffff', - zerolinewidth = 2, - gridcolor = 'ffff'), - bargap = 1) - -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 - -``` From b21aad40456d1bd2bcd0671147492b0956e90eb3 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 11:41:42 -0400 Subject: [PATCH 15/30] fix stock name --- r/2021-08-26-time-series.Rmd | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) 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')), From 250703b7c9e3ea2fbe3da179b6b4fff0d6304bd9 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 12:02:20 -0400 Subject: [PATCH 16/30] Delete 2021-08-04-network-graphs.Rmd --- ggplot2/2021-08-04-network-graphs.Rmd | 287 -------------------------- 1 file changed, 287 deletions(-) delete mode 100644 ggplot2/2021-08-04-network-graphs.Rmd 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 From e3c82bb586935d5860214daf3d234dfff3821fc0 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 12:34:22 -0400 Subject: [PATCH 17/30] Create 2021-08-18-discrete-colors.Rmd --- r/2021-08-18-discrete-colors.Rmd | 400 +++++++++++++++++++++++++++++++ 1 file changed, 400 insertions(+) create mode 100644 r/2021-08-18-discrete-colors.Rmd diff --git a/r/2021-08-18-discrete-colors.Rmd b/r/2021-08-18-discrete-colors.Rmd new file mode 100644 index 00000000..922d8408 --- /dev/null +++ b/r/2021-08-18-discrete-colors.Rmd @@ -0,0 +1,400 @@ +--- +description: How to use and configure discrete color sequences, also known as + categorical or qualitative color scales in R. +display_as: file_settings +has_thumbnail: true +language: r +layout: base +name: Discrete Colors +order: 21 +output: + html_document: + keep_md: true +permalink: r/discrete-color/ +thumbnail: thumbnail/heatmap_colorscale.jpg +--- + +```{r, echo = FALSE, message=FALSE} +knitr::opts_chunk$set(message = FALSE, warning = FALSE) +``` + +### Discrete vs Continuous Color + +In the same way as the X or Y position of a mark in cartesian coordinates can be used to represent continuous values (i.e. amounts or moments in time) or categories (i.e. labels), color can be used to represent continuous or discrete data. This page is about using color to represent **categorical** data using discrete colors, but Plotly can also [represent continuous values with color](https://plotly.com/r/colorscales/). + +### Discrete Color Concepts + +This document explains the following discrete-color-related concepts: + +- **color sequences** are lists of colors to be mapped onto discrete data values. No interpolation occurs when using color sequences, unlike with [continuous color scales](https://plotly.com/r/colorscales/), and each color is used as-is. Color sequence defaults depend on the `colors` attribute and can be explicitly specified using a vector of colors as argument. +- **legends** are visible representations of the mapping between colors and data values. Legend markers also change shape when used with various kinds of traces, such as symbols or lines for scatter-like traces. [Legends are configurable](https://plotly.com/r/legend/) under the `layout.legend` attribute. Legends are the discrete equivalent of [continuous color bars](https://plotly.com/r/colorscales/) + +### Discrete Color with Plotly + +Most Plotly functions accept a `color` argument which automatically assigns data values to discrete colors **if the data is non-numeric**. If the data is numeric, the color will automatically be considered [continuous](https://plotly.com/r/colorscales/). This means that numeric strings must be parsed to be used for continuous color, and conversely, numbers used as category codes must be converted to strings. + +For example, in the `tips` dataset, the `smoker` column contains strings: + +```{r} + +library(plotly) +library(reshape) +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, + gridcolor = 'ffff') ) +fig +``` + +The `size` column, however, contains numbers: + +```{r} + +library(plotly) +library(reshape) +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, + gridcolor = 'ffff') ) +fig +``` + +Converting this column to strings is very straightforward, but note that the ordering in the legend may not be sequential by default, but here it produces sequentially (see below for how to control discrete order): + +```{r} + +library(plotly) +library(reshape) +data("tips") + +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, + gridcolor = 'ffff') ) +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. + +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(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{ + 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) + } + }) +``` + +Use `app$run_server()` to run the dash app. + +### Color Sequences in Plotly + +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} + +library("RColorBrewer") +display.brewer.all(type = 'qual') + + +``` + + +Here is an example that creates a scatter plot using Plotly , with points colored using the built-in qualitative `accent` color sequence. + +```{r} + +library(plotly) +library(gapminder) +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, + gridcolor = 'ffff') ) +fig + +``` + +### Explicitly Constructing a Color Sequence + +The Plotly`colors` argument accepts explicitly-constructed color sequences as well, as lists of CSS colors: + +```{r} + +library(plotly) +library(gapminder) +data("gapminder") + +data <- gapminder[gapminder$year == 2007, ] + + +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") + ) %>% + 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, + gridcolor = 'ffff')) + +fig +``` + +**_Warning_**: If your color sequence has fewer colors than the number of unique values in the column you are mapping to `color`, the given colors will be mapped for some values and random colors will be mapped for other values : + +```{r} + +library(plotly) +data("tips") + +fig <- plot_ly(tips, x = ~total_bill, y = ~tip, type = 'scatter', mode = 'markers', color = ~day, + 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, + gridcolor = 'ffff')) + +fig +``` + +### Directly Mapping Colors to Data Values + +The example above assigned colors to data values on a first-come-first-served basis, but you can directly map colors to data values if this is important to your application with `colors`. Note that this does not change the order in which values appear in the figure or legend, as can be controlled below: + +```{r} + +library(plotly) +library(gapminder) +data("gapminder") + +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', + text = ~ country, + 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, + gridcolor = 'ffff')) + +fig + + +``` + +If your data set already contains valid CSS colors which you wish to use directly, you can pass the special value `"identity"` to `colors`, in which case the legend is hidden by default, and the color does not appear in the hover label: + +```{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, + gridcolor = 'ffff' + )) + +fig +``` + +### Controlling Discrete Color Order + +Plotly lets you specify an ordering over categorical variables with `categoryorder`, which will apply to colors and legends as well as symbols and [axes](https://plotly.com/r/axes/). This can be used with either `colors` or `color`. + +```{r} +library(plotly) +library(gapminder) +data("gapminder") + +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', + text = ~ country, + 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( + categoryorder = "array", + categoryarray = c("Asia","Oceania", "Europe", "Africa", "Americas"), + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + bargap = 1) + +fig + +``` + +```{r} + +library(plotly) +library(gapminder) +data("gapminder") + +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', + text = ~ country, + 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( + categoryorder = "array", + categoryarray = c("Asia","Oceania", "Europe", "Africa", "Americas"), + zerolinecolor = '#ffff', + zerolinewidth = 2, + gridcolor = 'ffff'), + bargap = 1) + +fig + +``` + From 9d9a965a229bd5d8dffc109663848446be15914f Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 12:35:57 -0400 Subject: [PATCH 18/30] add back file --- r/2021-07-26-ml-roc-pr.Rmd | 220 +++++++++++++++++++++++++++++++++++++ 1 file changed, 220 insertions(+) create mode 100644 r/2021-07-26-ml-roc-pr.Rmd diff --git a/r/2021-07-26-ml-roc-pr.Rmd b/r/2021-07-26-ml-roc-pr.Rmd new file mode 100644 index 00000000..65bf27de --- /dev/null +++ b/r/2021-07-26-ml-roc-pr.Rmd @@ -0,0 +1,220 @@ +--- +description: Interpret the results of your classification using Receiver Operating Characteristics (ROC) and Precision-Recall (PR) Curves in R with Plotly. +display_as: ai_ml +language: r +layout: base +name: ROC and PR Curves +order: 3 +output: + html_document: + keep_md: true +permalink: r/roc-and-pr-curves/ +thumbnail: thumbnail/ml-roc-pr.png +--- + +```{r, echo = FALSE, message=FALSE} +knitr::opts_chunk$set(message = FALSE, warning = FALSE) +``` +## ROC and PR Curves in R + +Interpret the results of your classification using Receiver Operating Characteristics (ROC) and Precision-Recall (PR) Curves in R with Plotly. + +## Preliminary plots + +Before diving into the receiver operating characteristic (ROC) curve, we will look at two plots that will give some context to the thresholds mechanism behind the ROC and PR curves. + +In the histogram, we observe that the score spread such that most of the positive labels are binned near 1, and a lot of the negative labels are close to 0. When we set a threshold on the score, all of the bins to its left will be classified as 0's, and everything to the right will be 1's. There are obviously a few outliers, such as **negative** samples that our model gave a high score, and *positive* samples with a low score. If we set a threshold right in the middle, those outliers will respectively become **false positives** and *false negatives*. + +As we adjust thresholds, the number of false positives will increase or decrease, and at the same time the number of true positives will also change; this is shown in the second plot. As you can see, the model seems to perform fairly well, because the true positive rate and the false positive rate decreases sharply as we increase the threshold. Those two lines each represent a dimension of the ROC curve. + + +```{r} +library(plotly) +library(tidymodels) +set.seed(0) +X <- matrix(rnorm(10000),nrow=500) +y <- sample(0:1, 500, replace=TRUE) +data <- data.frame(X,y) +data$y <- as.factor(data$y) +X <- subset(data,select = -c(y)) +logistic_glm <- + logistic_reg() %>% + set_engine("glm") %>% + set_mode("classification") %>% + fit(y ~ ., data = data) + +y_scores <- logistic_glm %>% + predict(X, type = 'prob') + +y_score <- y_scores$.pred_1 +db <- data.frame(data$y, y_score) + +z <- roc_curve(data = db, 'data.y', 'y_score') +z$specificity <- 1 - z$specificity +colnames(z) <- c('threshold', 'tpr', 'fpr') + +fig1 <- plot_ly(x= y_score, color = data$y, colors = c('blue', 'red'), type = 'histogram', alpha = 0.5, nbinsx = 50) %>% + layout(barmode = "overlay") +fig1 + +fig2 <- plot_ly(data = z, x = ~threshold) %>% + add_trace(y = ~fpr, mode = 'lines', name = 'False Positive Rate', type = 'scatter')%>% + add_trace(y = ~tpr, mode = 'lines', name = 'True Positive Rate', type = 'scatter')%>% + layout(title = 'TPR and FPR at every threshold') +fig2 <- fig2 %>% layout(legend=list(title=list(text=' Rate '))) +fig2 +``` + +## 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. + +```{r} +library(plotly) +library(tidymodels) +library(fastDummies) + +# Artificially add noise to make task harder +data(iris) +ind <- sample.int(150, 50) +samples <- sample(x = iris$Species, size = 50) +iris[ind,'Species'] = samples + +# Define the inputs and outputs +X <- subset(iris, select = -c(Species)) +iris$Species <- as.factor(iris$Species) + +# Fit the model +logistic <- + multinom_reg() %>% + set_engine("nnet") %>% + set_mode("classification") %>% + fit(Species ~ ., data = iris) + +y_scores <- logistic %>% + predict(X, type = 'prob') + +# One hot encode the labels in order to plot them +y_onehot <- dummy_cols(iris$Species) +colnames(y_onehot) <- c('drop', 'setosa', 'versicolor', 'virginica') +y_onehot <- subset(y_onehot, select = -c(drop)) + +z = cbind(y_scores, y_onehot) + +z$setosa <- as.factor(z$setosa) +roc_setosa <- roc_curve(data = z, setosa, .pred_setosa) +roc_setosa$specificity <- 1 - roc_setosa$specificity +colnames(roc_setosa) <- c('threshold', 'tpr', 'fpr') +auc_setosa <- roc_auc(data = z, setosa, .pred_setosa) +auc_setosa <- auc_setosa$.estimate +setosa <- paste('setosa (AUC=',toString(round(1-auc_setosa,2)),')',sep = '') + +z$versicolor <- as.factor(z$versicolor) +roc_versicolor <- roc_curve(data = z, versicolor, .pred_versicolor) +roc_versicolor$specificity <- 1 - roc_versicolor$specificity +colnames(roc_versicolor) <- c('threshold', 'tpr', 'fpr') +auc_versicolor <- roc_auc(data = z, versicolor, .pred_versicolor) +auc_versicolor <- auc_versicolor$.estimate +versicolor <- paste('versicolor (AUC=',toString(round(1-auc_versicolor,2)),')', sep = '') + +z$virginica <- as.factor(z$virginica) +roc_virginica <- roc_curve(data = z, virginica, .pred_virginica) +roc_virginica$specificity <- 1 - roc_virginica$specificity +colnames(roc_virginica) <- c('threshold', 'tpr', 'fpr') +auc_virginica <- roc_auc(data = z, virginica, .pred_virginica) +auc_virginica <- auc_virginica$.estimate +virginica <- paste('virginica (AUC=',toString(round(1-auc_virginica,2)),')',sep = '') + +# Create an empty figure, and iteratively add a line for each class +fig <- plot_ly()%>% + add_segments(x = 0, xend = 1, y = 0, yend = 1, line = list(dash = "dash", color = 'black'), showlegend = FALSE) %>% + add_trace(data = roc_setosa,x = ~fpr, y = ~tpr, mode = 'lines', name = setosa, type = 'scatter')%>% + add_trace(data = roc_versicolor,x = ~fpr, y = ~tpr, mode = 'lines', name = versicolor, type = 'scatter')%>% + add_trace(data = roc_virginica,x = ~fpr, y = ~tpr, mode = 'lines', name = virginica, type = 'scatter')%>% + layout(xaxis = list( + title = "False Positive Rate" + ), yaxis = list( + title = "True Positive Rate" + ),legend = list(x = 100, y = 0.5)) +fig + +``` + +In this example, we use the average precision metric, which is an alternative scoring method to the area under the PR curve. + +```{r} +library(plotly) +library(tidymodels) +library(fastDummies) + +# Artificially add noise to make task harder +data(iris) +ind <- sample.int(150, 50) +samples <- sample(x = iris$Species, size = 50) +iris[ind,'Species'] = samples + +# Define the inputs and outputs +X <- subset(iris, select = -c(Species)) +iris$Species <- as.factor(iris$Species) + +# Fit the model +logistic <- + multinom_reg() %>% + set_engine("nnet") %>% + set_mode("classification") %>% + fit(Species ~ ., data = iris) + +y_scores <- logistic %>% + predict(X, type = 'prob') + +y_onehot <- dummy_cols(iris$Species) +colnames(y_onehot) <- c('drop', 'setosa', 'versicolor', 'virginica') +y_onehot <- subset(y_onehot, select = -c(drop)) + +z = cbind(y_scores, y_onehot) + +z$setosa <- as.factor(z$setosa) +pr_setosa <- pr_curve(data = z, setosa, .pred_setosa) +aps_setosa <- mean(pr_setosa$precision) +setosa <- paste('setosa (AP =',toString(round(aps_setosa,2)),')',sep = '') + + +z$versicolor <- as.factor(z$versicolor) +pr_versicolor <- pr_curve(data = z, versicolor, .pred_versicolor) +aps_versicolor <- mean(pr_versicolor$precision) +versicolor <- paste('versicolor (AP = ',toString(round(aps_versicolor,2)),')',sep = '') + +z$virginica <- as.factor(z$virginica) +pr_virginica <- pr_curve(data = z, virginica, .pred_virginica) +aps_virginica <- mean(pr_virginica$precision) +virginica <- paste('virginica (AP = ',toString(round(aps_virginica,2)),')',sep = '') + +# Create an empty figure, and add a new line for each class +fig <- plot_ly()%>% + add_segments(x = 0, xend = 1, y = 1, yend = 0, line = list(dash = "dash", color = 'black'), showlegend = FALSE) %>% + add_trace(data = pr_setosa,x = ~recall, y = ~precision, mode = 'lines', name = setosa, type = 'scatter')%>% + add_trace(data = pr_versicolor,x = ~recall, y = ~precision, mode = 'lines', name = versicolor, type = 'scatter')%>% + add_trace(data = pr_virginica,x = ~recall, y = ~precision, mode = 'lines', name = virginica, type = 'scatter')%>% + layout(xaxis = list( + title = "Recall" + ), yaxis = list( + title = "Precision" + ),legend = list(x = 100, y = 0.5)) +fig +``` + + +## References + + +Learn more about histograms, filled area plots and line charts: + +* https://plot.ly/r/histograms/ + +* https://plot.ly/r/filled-area-plots/ + +* https://plot.ly/r/line-charts/ + + + + From 822ff61656be8b4f4913b066db53dee313d32b45 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 13:54:50 -0400 Subject: [PATCH 19/30] Create 2017-01-13-mixed-subplot.Rmd --- r/2017-01-13-mixed-subplot.Rmd | 102 +++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 r/2017-01-13-mixed-subplot.Rmd diff --git a/r/2017-01-13-mixed-subplot.Rmd b/r/2017-01-13-mixed-subplot.Rmd new file mode 100644 index 00000000..ac25832f --- /dev/null +++ b/r/2017-01-13-mixed-subplot.Rmd @@ -0,0 +1,102 @@ +--- +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! From 0fec8d3dbb6789fa7af20930753a8f43f63b992b Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 14:07:58 -0400 Subject: [PATCH 20/30] Update DESCRIPTION --- DESCRIPTION | 1 + 1 file changed, 1 insertion(+) diff --git a/DESCRIPTION b/DESCRIPTION index 96dd5447..09100087 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,7 @@ Package: Plotly's R graphing library. Imports: geomorph, + maptools, rjson, dplyr, quantmod, From b8715837644a2632410eedc35cb46b791a3393e9 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 14:16:09 -0400 Subject: [PATCH 21/30] fix treemap images --- ggplot2/2021-08-04-treemaps.Rmd | 8 -------- 1 file changed, 8 deletions(-) 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. From 343283a001b3e8c9d49bdf8d97db64b38c76445d Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 14:18:19 -0400 Subject: [PATCH 22/30] Update 2021-08-04-splom.Rmd --- ggplot2/2021-08-04-splom.Rmd | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) 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 From e37cf9fb79a4d19d81217a164395e04720a3194d Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 14:20:56 -0400 Subject: [PATCH 23/30] Update 2021-08-04-strip-charts.Rmd --- ggplot2/2021-08-04-strip-charts.Rmd | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ggplot2/2021-08-04-strip-charts.Rmd b/ggplot2/2021-08-04-strip-charts.Rmd index 8a307ebc..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() From 9741c8c3015dc025c679316a6c4bea93497083a9 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 14:28:20 -0400 Subject: [PATCH 24/30] Revert "Update DESCRIPTION" This reverts commit 0fec8d3dbb6789fa7af20930753a8f43f63b992b. --- DESCRIPTION | 1 - 1 file changed, 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 09100087..96dd5447 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,6 @@ Package: Plotly's R graphing library. Imports: geomorph, - maptools, rjson, dplyr, quantmod, From f11e2cede6644164f83af112456f5c5de9fe44fd Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 14:28:25 -0400 Subject: [PATCH 25/30] Revert "Create 2017-01-13-mixed-subplot.Rmd" This reverts commit 822ff61656be8b4f4913b066db53dee313d32b45. --- r/2017-01-13-mixed-subplot.Rmd | 102 --------------------------------- 1 file changed, 102 deletions(-) delete mode 100644 r/2017-01-13-mixed-subplot.Rmd diff --git a/r/2017-01-13-mixed-subplot.Rmd b/r/2017-01-13-mixed-subplot.Rmd deleted file mode 100644 index ac25832f..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! From 93686eb3ecade12d3d841def44efd95ec16a945f Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 14:45:04 -0400 Subject: [PATCH 26/30] Update 2021-08-18-discrete-colors.Rmd --- r/2021-08-18-discrete-colors.Rmd | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/r/2021-08-18-discrete-colors.Rmd b/r/2021-08-18-discrete-colors.Rmd index 922d8408..556b4df5 100644 --- a/r/2021-08-18-discrete-colors.Rmd +++ b/r/2021-08-18-discrete-colors.Rmd @@ -167,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') - - ``` From 42e257c9e58f621ded972565982714e9428ddb03 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 16:16:25 -0400 Subject: [PATCH 27/30] Update 2021-08-04-radar-chart.Rmd --- ggplot2/2021-08-04-radar-chart.Rmd | 63 ++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 16 deletions(-) diff --git a/ggplot2/2021-08-04-radar-chart.Rmd b/ggplot2/2021-08-04-radar-chart.Rmd index 79496517..9f24d727 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) @@ -110,3 +110,34 @@ ggplotly(p) ``` + +### What About Dash? + +[Dash for R](https://dashr.plot.ly/) 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 of the [`Graph` component](https://dashr.plot.ly/dash-core-components/graph) from the built-in `dashCoreComponents` package like this: + +```{r eval=FALSE} +library(plotly) + +fig <- plot_ly() +# fig <- fig %>% add_trace( ... ) +# fig <- fig %>% layout( ... ) + +library(dash) +library(dashCoreComponents) +library(dashHtmlComponents) + +app <- Dash$new() +app$layout( + htmlDiv( + list( + dccGraph(figure=fig) + ) + ) +) + +app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE) +``` From 360d4d67d363acd16cdcd64d4883d1a60a765128 Mon Sep 17 00:00:00 2001 From: Liam Connors Date: Tue, 28 May 2024 16:17:10 -0400 Subject: [PATCH 28/30] Update 2021-08-04-radar-chart.Rmd --- ggplot2/2021-08-04-radar-chart.Rmd | 31 ------------------------------ 1 file changed, 31 deletions(-) diff --git a/ggplot2/2021-08-04-radar-chart.Rmd b/ggplot2/2021-08-04-radar-chart.Rmd index 9f24d727..767e076b 100644 --- a/ggplot2/2021-08-04-radar-chart.Rmd +++ b/ggplot2/2021-08-04-radar-chart.Rmd @@ -110,34 +110,3 @@ ggplotly(p) ``` - -### What About Dash? - -[Dash for R](https://dashr.plot.ly/) 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 of the [`Graph` component](https://dashr.plot.ly/dash-core-components/graph) from the built-in `dashCoreComponents` package like this: - -```{r eval=FALSE} -library(plotly) - -fig <- plot_ly() -# fig <- fig %>% add_trace( ... ) -# fig <- fig %>% layout( ... ) - -library(dash) -library(dashCoreComponents) -library(dashHtmlComponents) - -app <- Dash$new() -app$layout( - htmlDiv( - list( - dccGraph(figure=fig) - ) - ) -) - -app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE) -``` From b076ea3a80a25fb969cbe3d0500f168e5891fd25 Mon Sep 17 00:00:00 2001 From: Greg Wilson Date: Fri, 7 Jun 2024 16:11:02 -0400 Subject: [PATCH 29/30] Update README.md with "maintained by community" badge --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) 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. + + From 939b034e388ba2bb1f87ff1d8377affc750b4ba8 Mon Sep 17 00:00:00 2001 From: Greg Wilson Date: Fri, 13 Dec 2024 11:15:14 -0500 Subject: [PATCH 30/30] adding code of conduct --- CODE_OF_CONDUCT.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 CODE_OF_CONDUCT.md 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 .