Plotly - Changing dropdowns disables groupings for boxplot - r

I'm creating a boxplot with dropdown options for the variable that gets plotted on the y axis. The data has 4 "people", and each observation has a type A or B. For each person 1:4, the chart plots bars for the observations A and B (example: https://plot.ly/r/box-plots/#grouped-box-plots).
I'm able to create it, but once I change the dropdown the groupings all get messed up. Here's example code:
library(plotly)
set.seed(123)
x <- rep(1:4, 6)
y1 <- rnorm(24, 5, 2)
y2 <- rnorm(24, 2, 5)
type <- rep(c("A", "A", "B", "B", "B", "B", "A", "A"), 3)
df <- data.frame(x, y1, y2, type)
p <- plot_ly(df, x = ~x) %>%
add_boxplot(y = ~y1, color = ~type, name = "First") %>%
add_boxplot(y = ~y2, color = ~type, name = "Second", visible = F) %>%
layout(
boxmode = "group",
title = "On/Off Box Plot",
xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.8,
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, FALSE)),
label = "y1"),
list(method = "restyle",
args = list("visible", list(FALSE, TRUE)),
label = "y2")))
)
)
p
The dropdown starts with y1 and looks exactly how I'd like, but changing the dropdown regroups the data and changing back to y1 doesn't get back to the original graph.
Here's what's happening to the groupings: After changing the dropdown, y1 groups all type "A" with y1 and y2 plotted next to each other. Option y2 does the same but uses type "B" data. I only want y1 data for both types A/B (like the original graph).
I'm guessing the ' boxmode = "group" ' line is getting lost during the switches, but I can't get it to work. Does anyone know how to maintain the groupings based on type? Thank you.

updatemenus should be length 4, because there are actually 4 traces (2 visible at a time). Note that for groups, each legend item has a corresponding trace. Unfortunately R's automatic repeating of vectors obscures this.
ie, the value for updatemenus should be:
updatemenus = list(
list(
y = 0.8,
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, TRUE, FALSE, FALSE)),
label = "y1"),
list(method = "restyle",
args = list("visible", list(FALSE, FALSE, TRUE, TRUE)),
label = "y2")))
)

Related

Plotly grouped barchart : how to create buttons to display different x values R

this is my dataframe :
artists <- c("Black Waitress", "Black Pumas")
tee_x<- c(20, 0)
tee_y <- c(3, 18)
tee_z <- c (30,0)
tee_t <- c(0,35)
data2 <- data.frame(artists, tee_x, tee_y,tee_t)
And this is what I am trying to create :
fig <- plot_ly(data=data2, x = ~artists, y = ~tee_x, type = 'bar', name = 'tee_x')
fig <- fig %>% add_trace(y = ~tee_y, name = 'tee_y')
fig <- fig %>% add_trace(y = ~tee_t, name = 'tee_t')
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group',
updatemenus = list(
list(
y = 0.8,
buttons = list(
list(method = "restyle",
args = list("x", list(data2[c(1),(2:4)])),
label = "Black Waitress"),
list(method = "restyle",
args = list("x", list(data2[c(2),(2:4)])),
label = "Black Pumas")))
))
fig
I am trying to create a grouper barplot in plotly which shows, for each artist the number of tees they sold and their type. I am also trying to create buttons so that you can look at individual artists instead of both of them. However it is not working and I have no clue how to solve the problem.
Thank you
EDIT :
I have been also trying this way
product <- c("tee_X","tee_y","tee_t")
artists <- c("Black Waitress", "Black Pumas")
Black_Waitress<- c(20, 0, 0)
Black_Pumas <- c(3, 18, 0)
tee_z <- c (30,0)
tee_t <- c(0,35)
data2 <- data.frame(product, Black_Waitress, Black_Pumas)
show_vec = c()
for (i in 1:length(artists)){
show_vec = c(show_vec,FALSE)
}
get_menu_list <- function(artists){
n_names = length(artists)
buttons = vector("list",n_names)
for(i in seq_along(buttons)){
show_vec[i] = TRUE
buttons[i] = list(list(method = "restyle",
args = list("visible", show_vec),
label = artists[i]))
print(list(show_vec))
show_vec[i] = FALSE
}
return_list = list(
list(
type = 'dropdown',
active = 0,
buttons = buttons
)
)
return(return_list)
}
print(get_menu_list(artists))
fig <- plot_ly(data=data2, x = ~product, y = ~Black_Waitress, type = 'bar')
fig <- fig %>% add_trace(y = ~Black_Pumas)
fig <- fig %>% layout(showlegend = F,yaxis = list(title = 'Count'), barmode = 'group',
updatemenus = get_menu_list(artists))
fig
However the problem is that when I choose an artist in the dropdown menu I want to be shown ONLY his/her products (in other words I would like to get rid of the 0 values dynamically) Is this possible?
Without the 0 Values and Initially Blank Plot
Essentially, you need to add a trace with no data. Additionally, since visibility settings were defined, all of that requires updating (because there are more traces now).
This can be further customized, of course. Here's a basic version of what I think you're looking for.
plot_ly(data = data3, x = ~artists, y = 0, type = "bar", color = ~tees,
visible = c(T, T, T)) %>%
add_bars(y = ~values, split = ~artists, # visibility F for all here
legendgroup = ~tees, name = ~tees, visible = rep(F, times = 4),
color = ~tees) %>%
layout(
yaxis = list(title = "Count"), barmode = "group",
updatemenus = list(
list(y = .8,
buttons = list(
list(method = "restyle", # there are 7 traces now; 3 blank
args = list(list(visible = c(F, F, F, F, T, F, T))),
label = "Black Waitress"),
list(method = "restyle",
args = list(list(visible = c(F, F, F, T, F, T, F))),
label = "Black Pumas")))))
Without the 0 Values
By your request, here is a version where the zero values are removed. First, I filtered the data for the non-zero values. This changed the number of traces from 6 to 4, so that needed to be accounted for in the areas where visibility is declared.
In this version, I only commented where there was something that changed from my original answer.
library(plotly)
library(tidyverse)
artists <- c("Black Waitress", "Black Pumas")
tee_x <- c(20, 0)
tee_y <- c(3, 18)
# tee_z <- c(30,0)
tee_t <- c(0,35)
data2 <- data.frame(artists, tee_x, tee_y, tee_t)
data3 <- pivot_longer(data2, col = starts_with("tee"),
names_to = "tees", values_to = "values") %>%
filter(values != 0) # <----- filter for non-zeros
plot_ly(data = data3, x = ~artists, y = ~values, split = ~artists,
legendgroup = ~tees, name = ~tees,
visible = rep(c(F, T), times = 2), # <---- 4 traces
color = ~tees, type = "bar") %>%
layout(
yaxis = list(title = "Count"), barmode = "group",
updatemenus = list(
list(y = .8,
buttons = list(
list(method = "restyle", # 4 traces
args = list(list(visible = c(F, T, F, T))),
label = "Black Waitress"),
list(method = "restyle", # 4 traces
args = list(list(visible = c(T, F, T, F))),
label = "Black Pumas")))))
With the 0 Values
I think it will be a lot easier to use visibility than trying to change out the data. If you wanted to see one artist at a time and use the dropdown to switch between the groups, this works.
First, I rearranged the data to make this easier. When I plotted it, I used split, so that the traces were split by the values on the x-axis, along with the colors. The traces are ordered artist 1, tee_t, artist 2, tee_t... and so on. When using visibility, you need the method restyle (because it's a trace attribute) and a declaration of true or false for each trace.
library(tidyverse)
library(plotly)
data3 <- pivot_longer(data2, col = starts_with("tee"),
names_to = "tees", values_to = "values")
plot_ly(data = data3, x = ~artists, y = ~values, split = ~artists,
legendgroup = ~tees, name = ~tees, visible = rep(c(F, T), times = 3),
color = ~tees, type = "bar") %>%
layout(
yaxis = list(title = "Count"), barmode = "group",
updatemenus = list(
list(y = .8,
buttons = list(
list(method = "restyle",
args = list(list(visible = c(F, T, F, T, F, T))),
label = "Black Waitress"),
list(method = "restyle",
args = list(list(visible = c(T, F, T, F, T, F))),
label = "Black Pumas")))))

Managing multiple Times Series with Crosstalk and plotly

I am trying to have a dynamic graph using plotly with crosstalk to show multiple times series. Depending on if a checkbox if checked or not, I would like the time series to be display on the graph or not.
In the code below, I created two times series 1 and 2 in the same dataframe (df_final).
I have two issues so far:
When none of the checkbox is checked, there is still a time series on
the graph
When both of the checkboxes are checked, instead of showing two times
series, the code considers that only 1 unique time series.
I don’t know how to improve any of the above, any ideas?
Also, I am not sure I am using the right tools (crosstalk, etc). Any other suggestions are welcomed.
library(plotly)
library(crosstalk)
#Create two identical dataframe
df_1 <- economics
df_2 <- economics
#Add a key to each dataframe to dissociate the two time series
df_1$ts <- 1
df_2$ts <- 2
#Modify the first dataframe
df_2$psavert <- economics$psavert + 1
df_final <- rbind(df_1, df_2)
shared_df_final <- SharedData$new(df_final)
bscols(
list(filter_checkbox("Time series", "Time series", shared_df_final, ~ts, inline = TRUE)),
plot_ly(data = shared_df_final, x = ~date, height = 700) %>%
add_lines(y = ~df_final$psavert, line = list(color = "#00526d", width = 1),
hoverinfo = "text", text = "ts")
)
Are you looking for something like that instead:
plot_ly() %>%
add_lines(data = df_1, x= ~date, y = ~psavert, name = "First") %>%
add_lines(data = df_2, x= ~date, y = ~psavert, name = "Second") %>%
layout(
updatemenus = list(
list(
y = 0.8,
type= 'buttons',
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, TRUE)),
label = "Both"),
list(method = "restyle",
args = list("visible", list(TRUE, FALSE)),
label = "First"),
list(method = "restyle",
args = list("visible", list(FALSE, TRUE)),
label = "Second")))
)
)

Plotly - Dynamically Choose X and Y Variables for Scatter Plot

I'm trying to create a scatter plot where the user can dynamically change the X and Y axis. I have it mostly completed, but I'm running into this weird hiccup.
The first time I change the X dropdown, the scatter plot will be incorrect. However, once I change the Y dropdown the scatter plot corrects itself, but it loses it's color-groupings. Example code:
# Get libraries
library(plotly)
set.seed(123)
index <- 1:24
x1 <- rnorm(24, 4, 3)
x2 <- rnorm(24, 3, 4)
y1 <- rnorm(24, 5, 2)
y2 <- rnorm(24, 2, 5)
type <- rep(c("A", "B", "C"), 8)
df <- data.frame(x1, x2, y1, y2, type)
p <- plot_ly(df, x = ~x1, y = ~y1, color = ~type, type = "scatter", mode = "markers",
text = ~paste("Index: ", index)) %>%
layout(
updatemenus = list(
## X Axis ##
list(
y = 0.6,
buttons = list(
list(method = "restyle",
args = list("x", list(df$x1)), # put it in a list
label = "x1"),
list(method = "restyle",
args = list("x", list(df$x2)), # put it in a list
label = "x2"))),
## Y Axis ##
list(
y = 0.5,
buttons = list(
list(method = "restyle",
args = list("y", list(df$y1)), # put it in a list
label = "y1"),
list(method = "restyle",
args = list("y", list(df$y2)), # put it in a list
label = "y2")))
))
p
After it pops up in your viewer, click the "X1" dropdown and select "X1" again: notice how the graph updates incorrectly. Next, click the "Y1" dropdown and select "Y1": notice how the graph looks the same as the original, but the color-groupings no longer exist and I believe the indexes got mixed up.
Is there an easy fix to what I'm doing wrong?

R interactive graph - remove a factor level\element and have axes adapt

I want to be able to present an interactive graph in R, which presents lines/bars/whatever of a measure grouped by a certain factor, and be able to make one or more of the factor's levels (groups) disappear AND have the x and y axes adapt to that, be responsive to this choice.
Example:
df <- data.frame(factor1 = c(rep("a", 3), rep("b", 3), rep("c", 3)),
xAxisVar = c(1:7, 5, 9),
yAxisVar = c(1:7, 5, 25))
ggplot(df, aes(xAxisVar, yAxisVar, group = factor1, color = factor1)) +
geom_line() +
geom_point()
In this graph the y axis is extended to reach 25 because of 1 "large" observation in factor level "c". I want to be able to press on "c" or filter it out AND have the y axis respond to that, re-rendering the plot reaching 6 or so.
I have tried plotly's ggplotly, you can automatically make group "c" disappear, but not have the plot re-rendering to account for that. Suggestions?
You mentioned ggplotly, so if you are open to plotly, you could try:
library(plotly)
library(reshape2)
#from long to wide
df_wide <- dcast(df, xAxisVar ~ factor1, value.var="yAxisVar")
plot_ly(df_wide, x = ~xAxisVar, y = ~a, name='a', type='scatter', mode='lines+markers') %>%
add_trace(y = ~b, name = 'b', type='scatter', mode='lines+markers') %>%
add_trace(y = ~c, name = 'c', type='scatter', mode='lines+markers', connectgaps = TRUE) %>%
layout(
updatemenus = list(
list(
type = "buttons",
x = -0.1,
y = 0.7,
label = 'Category',
buttons = list(
list(method = "restyle",
args = list('visible', c(TRUE, FALSE, FALSE)),
label = "a"),
list(method = "restyle",
args = list('visible', c(FALSE, TRUE, FALSE)),
label = "b"),
list(method = "restyle",
args = list('visible', c(FALSE, FALSE, TRUE)),
label = "c")
)
)))

plotly: Updating data with dropdown selection

I am not sure if this is possible, but here is what I would like to do. I would like to update the data in a plotly plot by selecting from a dropdown menu.
As a simple example, let's assume I have a data frame
df <- data.frame(x = runif(200), y = runif(200), z = runif(200))
from which I use df$x and df$y in a scatter plot. Two scenarios of data manipulation I would like to achieve using a dropdown:
Replace df$y with df$z
Plot only the first n values of df$x and df$y
I looked at the following two examples, which I can easily reproduce:
https://plot.ly/r/dropdowns/
However, I have no idea how to pass the information regarding the data to be plotted based on the dropdown selection. For scenario 2 e.g. I have tried it with args = list("data", df[1:n,]) which did not work.
For scenario 1 the (only?) way to go (according to the examples) seems to be hiding/showing the traces respectively. Is that the only way for scenario 2 as well?
Any alternative ideas?
Update 1: Add reproducible example
So here is an example which achieve what I would like in scenario 1.
require(plotly)
df <- data.frame(x = runif(200), y = runif(200), z = runif(200))
Sys.setenv("plotly_username"="xxx") #actual credentials replaced
Sys.setenv("plotly_api_key"="xxx") #actual credentials replaced
p <- plot_ly(df, x = df$x, y = df$y, mode = "markers", name = "A", visible = T) %>%
add_trace(mode = "markers", y = df$z, name = "B", visible = T) %>%
layout(
title = "Drop down menus - Styling",
xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = list(
list(method = "restyle",
args = list("visible", list(TRUE, TRUE)),
label = "Show All"),
list(method = "restyle",
args = list("visible", list(TRUE, FALSE)),
label = "Show A"),
list(method = "restyle",
args = list("visible", list(FALSE, TRUE)),
label = "Show B")))
))
plotly_POST(p)
Result here: https://plot.ly/~spietrzyk/96/drop-down-menus-styling/
This is based on the example from https://plot.ly/r/dropdowns/
However, I am wondering if one could pass the data to be plotted instead of triggering changes to the visible property of individual traces.
The one thing I tried was the following:
p <- plot_ly(df, x = df$x, y = df$y, mode = "markers", name = "A", visible = T) %>%
layout(
title = "Drop down menus - Styling",
xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = list(
list(method = "restyle",
args = list("y", df$y),
label = "Show A"),
list(method = "restyle",
args = list("y", df$z),
label = "Show B")))
))
Result here: https://plot.ly/~spietrzyk/98/drop-down-menus-styling/
This approach cannot work, as the data from df$z is not posted to the grid (https://plot.ly/~spietrzyk/99/).
So I was wondering is there anyway to manipulate the data to be plotted based on dropdown selection, beyond plotting all traces and than switching the visible property by dropdown selections.
Is this what you were after?
require(plotly)
df <- data.frame(x = runif(200), y = runif(200), z = runif(200))
p <- plot_ly(df, x = ~x, y = ~y, mode = "markers", name = "A", visible = T) %>%
layout(
title = "Drop down menus - Styling",
xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = list(
list(method = "restyle",
args = list("y", list(df$y)), # put it in a list
label = "Show A"),
list(method = "restyle",
args = list("y", list(df$z)), # put it in a list
label = "Show B")))
))
p
On the top of #jimmy G's answer.
You can automatically create the buttons so that you don't have to manually specify every single variable you want in the plot.
library(plotly)
df <- data.frame(x = runif(200), y = runif(200), z = runif(200), j = runif(200), k = rep(0.7, 200), i = rnorm(200,0.6,0.05))
create_buttons <- function(df, y_axis_var_names) {
lapply(
y_axis_var_names,
FUN = function(var_name, df) {
button <- list(
method = 'restyle',
args = list('y', list(df[, var_name])),
label = sprintf('Show %s', var_name)
)
},
df
)
}
y_axis_var_names <- c('y', 'z', 'j', 'k', 'i')
p <- plot_ly(df, x = ~x, y = ~y, mode = "markers", name = "A", visible = T) %>%
layout(
title = "Drop down menus - Styling",
xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = create_buttons(df, y_axis_var_names)
)
))
p
Hope you find it useful.

Resources