Home » Beautiful and selectable graphics with plotly and R

Beautiful and selectable graphics with plotly and R

Hi everybody how are you? Today I come to present you with a very simple and beautiful way to present our selectable graphics.

To perform this exercise we need the following libraries: plotly and crosstalk.

library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(crosstalk)

First of all we load our dataset to be able to play with the data. In this case, it is the number of sales per store in a country.

Example <- read.csv("Example.csv")
head(Example)
##   X      Shop Sales
## 1 1 Shop00002   374
## 2 2 Shop00005    84
## 3 3 Shop00007   142
## 4 4 Shop00008     0
## 5 5 Shop00009    67

And here the code with a brief explanation:

# Here we specify what the variable will be to select
Selectize <- SharedData$new(Example, ~Shop, "Select a Shop")
#In this place we created the graph
p <-  plot_ly(Selectize, color = ~Shop) %>%
  add_trace(x = ~Shop, y = ~Sales, type = 'bar',
             text = ~Sales, textposition = 'auto',
             marker = list(color = 'Shop',
                           line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
  layout(title = paste0("Sales by Shop"),
         barmode = 'group',
         xaxis = list(title = "Shop"),
         yaxis = list(title = "Sales"))
#Here we create the relationship between the selector and the graph
select <- highlight(
  ggplotly(p, tooltip = "Shop"), 
  selectize = TRUE, persistent = TRUE
)
## We recommend setting `persistent` to `FALSE` (the default) because persistent selection mode can now be used by holding the shift key (while triggering the `on` event).
#This helper function makes it easy to put HTML elements side by side.
bscols(select)
## Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8
## Returning the palette you asked for with that many colors

## Warning in RColorBrewer::brewer.pal(N, "Set2"): n too large, allowed maximum for palette Set2 is 8
## Returning the palette you asked for with that many colors
## Setting the `off` event (i.e., 'plotly_doubleclick') to match the `on` event (i.e., 'plotly_click'). You can change this default via the `highlight()` function.

And as they can be we obtain a selectable graph that allows us to analyze the results in a visual way. yo can see the result here!

Summary
Beautiful and selectable graphics with plotly and R
Article Name
Beautiful and selectable graphics with plotly and R
Description
Selectable graphics with plotly and R, A way to present data in a dynamic and useful way, Here one example with this tool. Rstudio and plotly
Author
Publisher Name
Blog-R
Publisher Logo