Helgi Guðmundsson
Helgi Guðmundsson

Reputation: 846

Interactively select a grouping variable in plotly

How can I create a grouped bar chart in plotly that has a dropdown (or something else), so a viewer can select the grouping variable?

Working example:

library(dplyr)
library(plotly)
library(reshape2)

iris$Sepal.L <- iris$Sepal.Length %>%
  cut(breaks = c(4,5,7,8),
      labels = c("Length.a","Length.b","Length.c"))
iris$Sepal.W <- iris$Sepal.Width %>%
  cut(breaks = c(1,3,5),
      labels = c("Width.a","Width.b"))

# Get percentages
data1 <- table(iris$Species, iris$Sepal.L) %>% 
  prop.table(margin = 1)
data2 <- table(iris$Species, iris$Sepal.W) %>% 
  prop.table(margin = 1)

# Convert to df
data1 <- data.frame(Var1=row.names(data1), cbind(data1))
row.names(data1) <- NULL
data2 <- data.frame(Var1=row.names(data2), cbind(data2))
row.names(data2) <- NULL

plot_ly(
  data = data1,
  name = "Length.a",
  x = ~Var1, y = ~Length.a,
  type = "bar") %>% 
  add_trace(y=~Length.b, name = "Length.b") %>% 
  add_trace(y=~Length.c, name = "Length.c")
plot_ly(
  data = data2,
  name = "Width.a",
  x = ~Var1, y = ~Width.a,
  type = "bar") %>% 
  add_trace(y=~Width.b, name = "Width.b")

For example if I would like to select between viewing a plot with table(iris$Species, iris$Sepal.Length) and a plot with table(iris$Species, iris$Sepal.Width) enter image description here enter image description here

Bonus:
If it's easy; being able to interactively select the x variable as well would be cool, but not necessary.

Upvotes: 1

Views: 1932

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24262

You can find a solution here. The idea is to plot your bar charts (with data1 and data2) all together and to make visible only one at a time.

items <- list(
           list(label="Var1", 
                args=list(list(visible=c(T,T,T,F,F)))),          
           list(label="Var2", 
                args=list(list(visible=c(F,F,F,T,T))))
         )

plot_ly(data=data1) %>%
  add_bars(name = "Length.a",
  x = ~Var1, y = ~Length.a, visible=T) %>%
  add_bars(name = "Length.b",
  x = ~Var1, y = ~Length.b, visible=T) %>%
  add_bars(name = "Length.c",
  x = ~Var1, y = ~Length.c, visible=T) %>%
  add_bars(name = "Width.a",
  x = ~Var1, y = ~Width.a, visible=F, data=data2, marker=list(color="#377EB8")) %>%
  add_bars(name = "Width.b",
  x = ~Var1, y = ~Width.b, visible=F, data=data2, marker=list(color="#FF7F00")) %>%
  layout(
    title = "Bar chart with drop down menu",
    xaxis = list(title="x"),
    yaxis = list(title = "y"),
    showlegend = T,
    updatemenus = list(
      list(y = 0.9,
           buttons = items)
    ))

enter image description here enter image description here

Upvotes: 4

Related Questions