Plotly

Los ejemplos son tomados de la página oficial de plotly, principalmente se obtienen algunos ejemplos gráficos con la estructura básica de plotly.

La función ggplotly() debe respetar ciertos criterios de ggplot, como texto (Para personalizar la información sobre los gráficos), frame (para crear animaciones ) e ID’s (para garantizar transiciones suaves y sensibles). Dado que ggplotly() del paquete ggplot2 devuelve un objeto qué se puede aplicar esencialmente a cualquier función del paquete R.

Existen algunos argumentos como:

\(\bullet\) layout() que sirve para personalizar el diseño del gráfico.

\(\bullet\) add_traces() y toda la estructura add_**(), por ejemplo add_polygons(), que sirven para agregar nuevos datos o gráficos.
\(\bullet\) subplot() para combinar múltiples objetos plotly.

\(\bullet\) Plotly_json() para inspeccionar el JSON subyacente enviado a plotly.js.

La función plot_ly () proporciona una interfaz más directa a plotly.js para que pueda aprovechar tipos de gráficos más especializados (por ejemplo, parallel coordinates o mapas) o incluso alguna visualización que la API en ggplot2 nunca admitirá (por ejemplo, surface, mesh, trisurf, etc.)

Este cheatsheet provee un resumen de los tipos de gráficos que están disponible en plotly.

Librerías

Line Plots

Line Plot

Basic Line Plot

Line Plots Mode

Style Line Plots

data<- data.frame(month = c('January', 'February', 'March', 'April', 'May', 'June', 'July',
                            'August', 'September', 'October', 'November', 'December'),
                  high_2000 = c(32.5, 37.6, 49.9, 53.0, 69.1, 75.4, 76.5, 76.6, 70.7, 60.6, 45.1, 29.3),
                  low_2000 = c(13.8, 22.3, 32.5, 37.2, 49.9, 56.1, 57.7, 58.3, 51.2, 42.8, 31.6, 15.9),
                  high_2007 = c(36.5, 26.6, 43.6, 52.3, 71.5, 81.4, 80.5, 82.2, 76.0, 67.3, 46.1, 35.0),
                  low_2007 = c(23.6, 14.0, 27.0, 36.8, 47.6, 57.7, 58.9, 61.2, 53.3, 48.5, 31.0, 23.6),
                  high_2014 = c(28.8, 28.5, 37.0, 56.8, 69.7, 79.7, 78.5, 77.8, 74.1, 62.6, 45.3, 39.9),
                  low_2014 = c(12.7, 14.3, 18.6, 35.5, 49.9, 58.0, 60.0, 58.6, 51.7, 45.2, 32.2, 29.1)) %>%
          mutate(month = factor(.$month,levels=.$month))

p <- plot_ly(data, 
              x = ~month, 
               y = ~high_2014, 
                name = 'High 2014', 
                 type = 'scatter', 
                  mode = 'lines',
                   line = list(color = 'rgb(199, 0, 57)', width = 4)) %>% 
        add_trace(y = ~low_2014,
                   name = 'Low 2014', 
                    line = list(color = 'rgb(59, 82, 128)', width = 4)) %>% 
        add_trace(y = ~high_2007, 
                   name = 'High 2007', 
                    line = list(color = 'rgb(199, 0, 57)', width = 4, dash = 'dash')) %>% 
        add_trace(y = ~low_2007, 
                   name = 'Low 2007', 
                    line = list(color = 'rgb(59, 82, 128)', width = 4, dash = 'dash')) %>% 
        add_trace(y = ~high_2000, 
                   name = 'High 2000', 
                    line = list(color = 'rgb(199, 0, 57) ', width = 4, dash = 'dot')) %>% 
        add_trace(y = ~low_2000, 
                   name = 'Low 2000', 
                    line = list(color = 'rgb(59, 82, 128)', width = 4, dash = 'dot')) %>% 
            layout(title = "Average High and Low Temperatures in New York",
                    xaxis = list(title = "Months"),
                      yaxis = list (title = "Temperature (degrees F)"))
p

Asignación de datos a tipo de línea

Connect Data Gaps

Opciones de interpolación de línea

Etiquetar líneas con anotaciones

data<-data.frame(x = c(2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013),
                 y_television = c(74, 82, 80, 74, 73, 72, 74, 70, 70, 66, 66, 69),
                 y_internet = c(13, 14, 20, 24, 20, 24, 24, 40, 35, 41, 43, 50))

p <- plot_ly(data, x = ~x) %>% 
        add_trace(y = ~y_television, 
                    type = 'scatter', 
                      mode = 'lines', 
                        line = list(color = 'rgba(199,0,57,1)', width = 2)) %>%
        add_trace(y = ~y_internet, 
                    type = 'scatter', 
                      mode = 'lines', 
                        line = list(color = 'rgba(49,130,189, 1)', width = 4)) %>% 
        add_trace(x = ~c(x[1], x[12]), 
                    y = ~c(y_television[1], y_television[12]), 
                      type = 'scatter', 
                        mode = 'markers', 
                          marker = list(color = 'rgba(199,0,57,1)', size = 8)) %>% 
        add_trace(x = ~c(x[1], x[12]), 
                    y = ~c(y_internet[1], y_internet[12]), 
                      type = 'scatter', 
                        mode = 'markers', 
                          marker = list(color = 'rgba(49,130,189, 1)', size = 12)) %>% 
            layout(title = "Main Source for News", 
                    xaxis = list(title = "",
                                 showline = TRUE,
                                 showgrid = FALSE,
                                 showticklabels = TRUE,
                                 linecolor = 'rgb(204, 204, 204)',
                                 linewidth = 2,
                                 autotick = FALSE,
                                 ticks = 'outside',
                                 tickcolor = 'rgb(204, 204, 204)',
                                 tickwidth = 2,
                                 ticklen = 5,
                                 tickfont = list(family = 'Arial',
                                 size = 12,
                                 color = 'rgb(82, 82, 82)')), 
                      yaxis = list(title = "",
                                   showgrid = FALSE,
                                   zeroline = FALSE,
                                   showline = FALSE,
                                   showticklabels = FALSE), 
                        margin = list(autoexpand = FALSE,
                                      l = 100,
                                      r = 100,
                                      t = 110),
                          autosize = FALSE,
                            showlegend = FALSE,
                              annotations = list(xref = 'paper', #television 1
                                                 yref = 'y',
                                                 x = 0.05,
                                                 y = data$y_television[1],
                                                 xanchor = 'right',
                                                 yanchor = 'middle',
                                                 text = ~paste('Television ', data$y_television[1], '%'),
                                                 font = list(family = 'Arial',
                                                             size = 16,
                                                             color = 'rgba(199,0,57,1)'),
                                                 showarrow = FALSE)) %>% 
            layout(annotations = list(xref = 'paper', # internet 1
                                 yref = 'y',
                                 x = 0.05,
                                 y = data$y_internet[1],
                                 xanchor = 'right',
                                 yanchor = 'middle',
                                 text = ~paste('Internet ', data$y_internet[1], '%'),
                                 font = list(family = 'Arial',
                                             size = 16,
                                             color = 'rgba(49,130,189, 1)'),
                   showarrow = FALSE)) %>% 
            layout(annotations = list(xref = 'paper', #television2
                                      x = 0.95,
                                      y = data$y_television[12],
                                      xanchor = 'left',
                                      yanchor = 'middle',
                                      text = paste('Television ', data$y_television[12], '%'),
                                      font = list(family = 'Arial',
                                                  size = 16,
                                                  color= 'rgba(199,0,57,1)'),
                                      showarrow = FALSE)) %>% 
            layout(annotations = list(xref = 'paper',  # internet 2
                                      x = 0.95,
                                      y = data$y_internet[12],
                                      xanchor = 'left',
                                      yanchor = 'middle',
                                      text = paste('Internet ', data$y_internet[12], '%'),
                                      font = list(family = 'Arial',
                                                  size = 16,
                                                  color =  'rgba(49,130,189, 1)'),
                                      showarrow = FALSE))
p

Scatter plot with smoothing line

Filled Lines

Density Plot

Time Series

También se pueden inclustar plots.

Forecasting

Bubble Charts

Utilizando la función ggplot

La función plotly_build ayuda a modificar la descripción de cada punto de la información de cada variable, así que, puede ser útil para anular los valores predeterminados por ggplotly o para depurar errores de representación.

Discrete Scatter Plot

Continuous Scatter Plot

Asignación de una variable de color (Continua)

Asignación de una variable de color (categórica)

Escalando el tamaño de los gráficos de burbujas

Escalado con la función sizeref

Para escalar el tamaño de la burbuja, se usa el atributo sizeref. Es recomendable usar la siguiente fórmula para calcular un valor de sizeref .

\[sizeref = 2.0 *\frac{\text{max (matriz de valores de tamaño)}} {\text{tamaño de marcador máximo deseado ** 2}}\] Tenga en cuenta que establecer sizeref en un valor mayor que 1 disminuye los tamaños de marcador representados, mientras establece sizeref en menos de 1 aumenta el tamaño de los marcadores renderizados. Consulte https://plotly.com/python/reference/#scatter-marker-sizeref para obtener más información.

Texto flotante en el gráficos de burbujas

Styled Bubble Chart

Dot Plots

Basic dot plot

Dot and Dumbbell Plots

Graphing Multiple Chart

Scatter and Line Plots

Basic Scatter Plot

Styled Scatter Plot

Plotting Markers and Lines

También es posible pasar el primer gráfico en la función plot_ly. En tales casos, se debe especificar el tipo de gráfico, como se muestra a continuación:

Qualitative Colorscales

ColorBrewer Palette Names

Custom Color Scales

Mapping Data to Symbols

Adding Color and Size Mapping

Data Labels on Hover

Bar and Line Chart

Bar and Line Chart

Scatterplot with Loess Smoother

Loess Smoother with Uncertainty Bounds

Log Plots

Bar Charts

Vertical Bar Chart

Basic Bar Chart

Gráfico de barras agrupadas

Gráfico de barras apiladas

Gráfico de barras con texto emergente

Gráfico de barras con etiquetas directas

Gráfico de barras agrupadas con etiquetas directas

Etiquetas rotadas de gráfico de barras

Personalizar el color del gráfico de barra

Personalizar anchos de barra individuales

Personalizar la base de barra individual

Asignación de una variable de color

Gráfico de barras de color y estilo

Gráfico de barras en cascada

Horizontal Bar Chart

ejemplos de gráficos de barras horizontales https://plotly.com/r/horizontal-bar-charts/

Basic Horizontal Bar Chart

Gráfico de barras horizontales coloreadas

Paleta de colores para gráfico de barras

data<- data.frame(y = c('The course was effectively<br>organized',
                        'The course developed my<br>abilities and skills for<br>the subject',
                        'The course developed my<br>ability to think critically about<br>the subject',
                        'I would recommend this<br>course to a friend'),
                  x1 = c(21, 24, 27, 29),
                  x2 = c(30, 31, 26, 24),
                  x3 = c(21, 19, 23, 15),
                  x4 = c(16, 15, 11, 18),
                  x5 = c(12, 11, 13, 14))

top_labels = c('Strongly<br>agree', 'Agree', 'Neutral', 'Disagree', 'Strongly<br>disagree')

p <- data%>% 
        plot_ly(x = ~x1, 
                  y = ~y, 
                    type = 'bar', 
                      orientation = 'h',
                        marker = list(color = 'rgba(38, 24, 74, 0.8)',
                                      line = list(color = 'rgb(248, 248, 249)', width = 1))) %>% 
        add_trace(x = ~x2, 
                    marker = list(color = 'rgba(71, 58, 131, 0.8)')) %>% 
          add_trace(x = ~x3, 
                      marker = list(color = 'rgba(122, 120, 168, 0.8)')) %>% 
            add_trace(x = ~x4, 
                        marker = list(color = 'rgba(164, 163, 204, 0.85)')) %>% 
              add_trace(x = ~x5, marker = list(color = 'rgba(190, 192, 213, 1)')) %>% 
                  layout(xaxis = list(title = "",
                                      showgrid = FALSE,
                                      showline = FALSE,
                                      showticklabels = FALSE,
                                      zeroline = FALSE,
                                      domain = c(0.15, 1)),
                         yaxis = list(title = "",
                                      showgrid = FALSE,
                                      showline = FALSE,
                                      showticklabels = FALSE,
                                      zeroline = FALSE),
                            barmode = 'stack',
                              paper_bgcolor = 'rgb(248, 248, 255)', 
                                plot_bgcolor = 'rgb(248, 248, 255)',
                                  margin = list(l = 120, r = 10, t = 140, b = 80),
                                    showlegend = FALSE) %>% 
                      add_annotations(xref = 'paper',   # labeling the y-axis
                                        yref = 'y', 
                                          x = 0.14, 
                                            y = data$y,
                                              xanchor = 'right',
                                                text = data$y,
                                                  font = list(family = 'Arial', 
                                                              size = 12, 
                                                              color = 'rgb(67, 67, 67)'),
                                                    showarrow = FALSE, 
                                                      align = 'right') %>% 
                      add_annotations(xref = 'x',  # labeling the percentages of each bar (x_axis)
                                       yref = 'y',   
                                        x = data$x1 / 2, 
                                         y = data$y,
                                          text = paste(data[,"x1"], '%'),
                                           font = list(family = 'Arial', 
                                                       size = 12,
                                                       color = 'rgb(248, 248, 255)'),
                                             showarrow = FALSE) %>% 
                      add_annotations(xref = 'x', 
                                       yref = 'y',
                                        x = data$x1 + data$x2 / 2, 
                                         y = data$y,
                                          text = paste(data[,"x2"], '%'),
                                            font = list(family = 'Arial', 
                                                        size = 12,
                                                        color = 'rgb(248, 248, 255)'),
                                              showarrow = FALSE)  %>% 
                      add_annotations(xref = 'x',
                                       yref = 'y',
                                        x = data$x1 + data$x2 + data$x3 / 2, 
                                         y = data$y,
                                          text = paste(data[,"x3"], '%'),
                                            font = list(family = 'Arial', 
                                                        size = 12,
                                                        color = 'rgb(248, 248, 255)'),
                                              showarrow = FALSE) %>% 
                      add_annotations(xref = 'x', 
                                       yref = 'y',
                                        x = data$x1 + data$x2 + data$x3 + data$x4 / 2, 
                                         y = data$y,
                                          text = paste(data[,"x4"], '%'),
                                            font = list(family = 'Arial', 
                                                        size = 12,
                                                        color = 'rgb(248, 248, 255)'),
                                              showarrow = FALSE) %>% 
                      add_annotations(xref = 'x', 
                                       yref = 'y',
                                        x = data$x1 + data$x2 + data$x3 + data$x4 + data$x5 / 2, 
                                         y = data$y,
                                          text = paste(data[,"x5"], '%'),
                                            font = list(family = 'Arial', 
                                                        size = 12,
                                                        color = 'rgb(248, 248, 255)'),
                                              showarrow = FALSE) %>% 
                      add_annotations(xref = 'x', # labeling the first Likert scale (on the top)
                                       yref = 'paper', 
                                        x = c(21 / 2, 
                                              21 + 30 / 2,
                                              21 + 30 + 21 / 2,
                                              21 + 30 + 21 + 16 / 2,
                                              21 + 30 + 21 + 16 + 12 / 2),
                                          y = 1.15,
                                           text = top_labels,
                                             font = list(family = 'Arial', 
                                                         size = 12,
                                                         color = 'rgb(67, 67, 67)'),
                                               showarrow = FALSE)
p

Bar Chart with Line Plot

data<- data.frame(y = c('Japan', 'United Kingdom', 'Canada', 'Netherlands', 'United States', 
                        'Belgium', 'Sweden', 'Switzerland'),
                  x_saving =c(1.3586, 2.2623000000000002, 4.9821999999999997, 6.5096999999999996,
                              7.4812000000000003, 7.5133000000000001, 15.2148, 17.520499999999998), 
                  x_net_worth = c(93453.919999999998, 81666.570000000007, 69889.619999999995, 78381.529999999999,
                              141395.29999999999, 92969.020000000004, 66090.179999999993, 122379.3))

p1 <- data%>% 
        plot_ly(x = ~x_saving,
                  y = ~reorder(y, x_saving),
                    name = 'Household savings, percentage of household disposable income',
                      type = 'bar',
                        orientation = 'h',
                          marker = list(color = 'rgba(50, 171, 96, 0.6)',
                                        line = list(color = 'rgba(50, 171, 96, 1.0)', width = 1))) %>%
            layout(yaxis = list(showgrid = FALSE, 
                                showline = FALSE, 
                                showticklabels = TRUE, 
                                domain= c(0, 0.85)),
                     xaxis = list(zeroline = FALSE, 
                                  showline = FALSE, 
                                  showticklabels = TRUE, 
                                  showgrid = TRUE)) %>% 
                add_annotations(xref = 'x1', 
                                 yref = 'y',
                                  x = data$x_saving * 2.1 + 3, 
                                   y = data$y,
                                    text = paste(round(data$x_saving, 2), '%'),
                                      font = list(family = 'Arial', 
                                                  size = 12, 
                                                  color = 'rgb(50, 171, 96)'),
                                                  showarrow = FALSE)

p2 <- data%>%
        plot_ly(x = ~x_net_worth, 
                 y = ~reorder(.$y, .$x_saving), 
                  name = 'Household net worth, Million USD/capita',
                   type = 'scatter', 
                    mode = 'lines+markers',
                      line = list(color = 'rgb(128, 0, 128)')) %>% 
          layout(yaxis = list(showgrid = FALSE, 
                              showline = TRUE, 
                              showticklabels = FALSE,
                              linecolor = 'rgba(102, 102, 102, 0.8)', 
                              linewidth = 2,
                              domain = c(0, 0.85)),
                    xaxis = list(zeroline = FALSE, 
                                 showline = FALSE, 
                                 showticklabels = TRUE, 
                                 showgrid = TRUE,
                                 side = 'top', 
                                 dtick = 25000)) %>% 
              add_annotations(xref = 'x2',
                                yref = 'y',
                                  x = data$x_net_worth, 
                                    y = data$y,
                                      text = paste(data$x_net_worth, 'M'),
                                        font = list(family = 'Arial', 
                                                    size = 12, 
                                                    color = 'rgb(128, 0, 128)'), showarrow = FALSE)

p <- subplot(p1, p2) %>% 
       layout(title = 'Household savings & net worth for eight OECD countries',
                legend = list(x = 0.029, 
                               y = 1.038,
                                font = list(size = 10)),
                  margin = list(l = 100, r = 20, t = 70, b = 70),
                    paper_bgcolor = 'rgb(248, 248, 255)',
                      plot_bgcolor = 'rgb(248, 248, 255)') %>% 
          add_annotations(xref = 'paper', 
                            yref = 'paper',
                              x = -0.14, 
                                y = -0.15,
                                  text = paste('OECD (2015), Household savings (indicator), Household net worth (indicator). doi: 10.1787/cfc6f499-en (Accessed on 05 June 2015)'),
                                    font = list(family = 'Arial', 
                                                size = 10, 
                                                color = 'rgb(150,150,150)'),
                                      showarrow = FALSE)
p

Area Plots

Para generar un rellenar el interior de un plot de área, se usa el atributo fill='tozeroy'.

Basic Filled Area Plot

Filled Area Plot with Multiple Traces

Selecting Hover Points

Seleccionando puntos flotantes

Custom Colors

Area Plot without Lines

Para crear un gráfico de área sin líneas se utiliza el atributo mode="none".

Relleno interior para gráfico de área

Gráficos de área apiladas

Gráfico de área apilada con valores acumulativos

Histogram

Basic Histogram

Función específica de agrupamiento

Horizontal Histogram

Overlaid Histograms

Cumulative Histogram

Share bins between histograms

En este ejemplo, ambos histogramas tienen una configuración bin compatible con el atributo bingroup.

Los gráficos en la mismo subtrama y con la misma barmode ('stack', 'relative', 'gruop') se fuerzan en la misma bingroup, sin embargo, con barmode = 'overlay' y en diferentes ejes (del mismo tipo de eje) pueden tener configuraciones de bin compatibles.

Boxplot

Basic Boxplot

Algoritmo para el calculo de cuartiles

El algoritmo quartilemethod='exclusive' utiliza la mediana para dividir el conjunto de datos ordenado en dos mitades. Si la muestra es impar, no incluye la mediana en ninguna de las dos. Q1 es entonces la mediana de la mitad inferior y Q3 es la mediana de la mitad superior.

El algoritmo quartilemethod='inclusive' también usa la mediana para dividir el conjunto de datos ordenado en dos mitades, pero si la muestra es impar, incluye la mediana en ambas mitades. Q1 es entonces la mediana de la mitad inferior y Q3 la mediana de la mitad superior.

Modificación del algoritmo para calcular cuartiles

Box Plots con cuartiles precalculados

Esto puede ser útil si ya se ha calculado previamente esos valores o si necesita utilizar un algoritmo diferente al proporcionado.

Horizontal Boxplot

Adding Jittered Points

Several Box Plots

Grouped Box Plots

Styling Outliers

data<- data.frame(y1 = c(0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
                         8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25),
                  y2 = c(0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
                         8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25),
                  y3 = c(0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
                         8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25),
                  y4 = c(0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
                         8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25))

p <- data%>% 
        plot_ly(type = 'box') %>% 
            add_boxplot(y = ~y1, 
                          jitter = 0.6, 
                            pointpos = -1.8, 
                              boxpoints = 'all',
                                marker = list(color = 'rgba(147,151,144,0.5)',
                                              size=8,
                                              line = list(color = 'rgba(147,151,144,1)')),
                                  name = "All Points") %>% 
            add_boxplot(y = ~y2,
                          name = "Only Whiskers", 
                            boxpoints = FALSE,
                              marker = list(color = 'rgba(255,87,51,0.5)',
                                        line = list(outliercolor = 'rgba(255,87,51,1)',
                                                    color = 'rgba(255,87,51,1)'))) %>%
            add_boxplot(y = ~y3, 
                          name = "Suspected Outlier", 
                            boxpoints = 'suspectedoutliers',
                              marker = list(color = 'rgba(244,12,12,0.5)',
                                            outliercolor = 'rgba(244,12,12,0.5)',
                                            line = list(outliercolor = 'rgba(244,12,12,1)',
                                                        outlierwidth = 2))) %>% 
           add_boxplot(y = ~y4, 
                          name = "Whiskers and Outliers", 
                            boxpoints = 'outliers',
                              marker = list(color = 'rgba(199,0,57,0.5)',
                                            line = list(outliercolor = 'rgba(199,0,57,0.5)',
                                                        color = 'rgba(199,0,57,0.5)'))) %>%
                layout(title = "Box Plot Styling Outliers")
p

Pie Chart

Styled Pie Chart

Subplots

Para crear los subplots de un gráfico de pie, se debe usar el dominio. Es importante tener en cuenta que la matriz \(X\) establece la posición horizontal mientras que la matriz \(Y\) establece la posición vertical. Por ejemplo, \(x=[0,0.5]\), \(y=[0,0.5]\) significaría que la posición del gráfico inferior-izquierda.

Este ejemplo utiliza un atributo de grid para los suplots. Se hace referencia al destino de fila y columna utilizando el atributo domain.

Orientación del texto

El atributo insdetextorientation controla la orientación del texto dentro de los sectores. \(\bullet\) 'auto', las etiquetas pueden rotarse automáticamente para ajustarse al tamaño máximo dentro del corte.
\(\bullet\) 'horizontal', "Radial", "Tangencial" obliga al texto a ser horizonatal, radial o tangencial.

plotly puede reducir el tamaño de fuente para ajustar el texto con la orientaciión solicitada.

Gráfico de donas

Para obtener más información y opciones de atributos de gráficos plotly_attributes

Heatmaps

Basic Heatmap

Categorical Axes

Escalas de colores secuenciales: grises

Escalas de colores personalizadas

Violin Plots

Basic Violin Plot

Multiple Trace

Grouped Violin Plot

Split Violin Plot

Advanced Violin Plot

df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")

pointposMale <- c(-0.9,-1.1,-0.6,-0.3)
pointposFemale <- c(0.45,1.2,1,0.4)
showLegend <- c(T,F,F,F)

p<-NULL
i = 0
for (i in 1:length(unique(df$day))) {
 p[[i]] <- plot_ly(type = 'violin') %>%
        add_trace(x = df$day[df$sex == 'Male' & df$day == unique(df$day)[i]],
                    y = df$total_bill[df$sex == 'Male' & df$day == unique(df$day)[i]],
                      hoveron = "points+kde",
                        legendgroup = 'M',
                          scalegroup = 'M',
                            name = 'M',
                              side = 'negative',
                                box = list(visible = T),
                                  points = 'all',
                                    pointpos = pointposMale[i],
                                      jitter = 0,
                                        scalemode = 'count',
                                          meanline = list(visible = T),
                                            color = I("#8dd3c7"),
                                              marker = list(line = list(width = 2, color = "#8dd3c7"),
                                                            symbol = 'line-ns'),
                                                showlegend = showLegend[i]) %>%
          add_trace(x = df$day[df$sex == 'Female' & df$day == unique(df$day)[i]],
                      y = df$total_bill[df$sex == 'Female' & df$day == unique(df$day)[i]],
                        hoveron = "points+kde",
                          legendgroup = 'F',
                            scalegroup = 'F',
                              name = 'F',
                                side = 'positive',
                                  box = list(visible = T),
                                    points = 'all',
                                      pointpos = pointposFemale[i],
                                        jitter = 0,
                                          scalemode = 'count',
                                            meanline = list(visible = T),
                                              color = I("#bebada"),
                                                marker = list(line = list(width = 2, color = "#bebada"),
                                                              symbol = 'line-ns'),
                                                  showlegend = showLegend[i]) %>%
              layout(title = "Total bill distribution<br><i>scaled by number of bills per gender",
                      yaxis = list(zeroline = F),
                        xaxis = list(range=c(-0.8,0.8)),
                        violingap = 0,
                          violingroupgap = 0,
                            violinmode = 'overlay',
                              legend = list(tracegroupgap = 0))
}
t<-subplot(p[[1]],p[[2]],p[[3]],p[[4]],nrows = 1,shareY = TRUE, margin = 0)
t

Error Bars

Bar Chart with Error Bars

Scatterplot with Error Bars

Line Graph with Error Bars

Splom

Una matriz de scatterplots, esta asociada a \(n\) matrices númericas \(X^{1},X^{2},...,X^{n}\) de la misma longuitud.

La etiqueta en cada dimensión se asigna a los títulos de los ejes de la celda de cada matriz correspondiente.

El texto es una cadena única asignada a todos los puntos mostrados por splom o una lista de cadenas de la misma longitud que las dimensiones, \(X_{i}\). El text[k] es la información sobre herramientas para el \(k^{th}\) punto en cada celda.

El marker establece los atributos de los marcadores en todos los gráficos de dispersión.

Splom of the Iris data set

Se Define una escala de colores discreta con tres colores correspondientes a las tres clases de flores:

Los gráficos de dispersión en la diagonal principal se pueden eliminar configurando diagonal=list(visible=FALSE)

Para trazar solo la mitad inferior / superior del splom se cambia el valor predeterminado showlowerhalf=TRUE/ showupperhalf=FALSE:

Cada lista en las dimensiones tiene una clave, visible, establecida de forma predeterminada en visible=TRUE. Se puede elegir eliminar una variable de splom, configurando visible=FALSE su dimensión correspondiente. En este caso, la cuadrícula predeterminada asociada a la matriz de diagrama de dispersión mantiene su número de celdas, pero las celdas en la fila y columna correspondientes a la dimensión falsa visible están vacías:

Splom for the diabetes dataset

El conjunto de datos sobre diabetes se descarga de kaggle . Se utiliza para predecir la aparición de diabetes en base a 8 medidas de diagnóstico. El archivo de diabetes contiene las medidas de diagnóstico para 768 pacientes, que están etiquetados como no diabéticos (Outcome = 0), respectivamente, diabéticos (Outcome = 1). El splom asociado a las 8 variables puede ilustrar la fuerza de la relación entre pares de medidas para pacientes diabéticos / no diabéticos.

Se define una escala de colores discreta con dos colores: azul para no diabéticos y rojo para diabéticos:

df = read.csv('https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv')

pl_colorscale = list(c(0.0, '#119dff'),
                  c(0.5, '#119dff'),
                  c(0.5, '#ef553b'),
                  c(1, '#ef553b'))
axis = list(showline=FALSE,
            zeroline=FALSE,
            gridcolor='#ffff',
            ticklen=4,
            titlefont=list(size=13))

p <- df %>%
       plot_ly() %>%
          add_trace(type = 'splom',
                      dimensions = list(list(label='Pregnancies', values=~Pregnancies),
                                        list(label='Glucose', values=~Glucose),
                                        list(label='BloodPressure', values=~BloodPressure),
                                        list(label='SkinThickness', values=~SkinThickness),
                                        list(label='Insulin', values=~Insulin),
                                        list(label='BMI', values=~BMI),
                                        list(label='DiabPedigreeFun', values=~DiabetesPedigreeFunction),
                                        list(label='Age', values=~Age)),
                          text=~factor(Outcome, labels=c("non-diabetic","diabetic")),
                            diagonal=list(visible=F),
                              marker = list(color = ~Outcome,
                                            colorscale = pl_colorscale,
                                            size = 5,
                                            line = list(width = 1, color = 'rgb(230,230,230)'))) %>%
                layout(title = "Scatterplot Matrix (SPLOM) for Diabetes Dataset<br>Data source: <a href='https://www.kaggle.com/uciml/pima-indians-diabetes-database/data'>[1]</a>",
                          hovermode='closest',
                            dragmode = 'select',
                              plot_bgcolor='rgba(240,240,240, 0.95)',
                                xaxis=list(domain=NULL, 
                                           showline=F,
                                           zeroline=F, 
                                           gridcolor='#ffff',
                                           ticklen=4, 
                                           titlefont=list(size=13)),
                                yaxis=list(domain=NULL,
                                           showline=F, 
                                           zeroline=F, 
                                           gridcolor='#ffff', 
                                           ticklen=4, 
                                           titlefont=list(size=13)),
                                xaxis2=axis,
                                xaxis3=axis,
                                xaxis4=axis,
                                xaxis5=axis,
                                xaxis6=axis,
                                xaxis7=axis,
                                xaxis8=axis,
                                yaxis2=axis,
                                yaxis3=axis,
                                yaxis4=axis,
                                yaxis5=axis,
                                yaxis6=axis,
                                yaxis7=axis,
                                yaxis8=axis)
p

2d Histogram

Basic 2D Histogram

Los histogramas 2D requieren \(x/y\), pero a diferencia de los mapas de calor, \(z\) es opcional. Si \(z\) no se proporciona, el binning se produce en el navegador.

Colorscale

2d Density

Contour Plots

Basic Contour

Establecer coordenadas X e Y

Establecer el tamaño y rango del contorno

Smoothing Contour Lines

Smoothing Contour Coloring

Add Contour Labels

Create Matrix and Plot Contour

2D Density Contour Plot

3d Surface Plots

Basic 3D Surface Plot

Surface Plot With Contours

2D Kernel Density Estimation

Configurar los niveles de la superficie de los contornos

Este ejemplo muestra cómo cortar el gráfico de superficie en la posición deseada para cada uno de los ejes \(x\), \(y\) y \(z\).

contours.x.start establece el valor inicial del nivel de contorno,
end establece el final y
size establece el step entre cada nivel de contorno.

Multiple Surfaces

Referencias

Plotly R Graphing Library | R | Plotly. (n.d.). Retrieved August 5, 2020, from https://plotly.com/r/