I have a dataframe listing the number of individual engagements made with 49 different committees over 5 years. An example with a reduced number of categories is provided below:
library(dplyr)
df <- data.frame(Year = c(2019, 2020, 2021, 2022, 2023),
Committees = c("House Foreign Affairs",
"House Foreign Affairs",
"House Foreign Affairs",
"House Foreign Affairs",
"House Foreign Affairs",
"House Judiciary",
"House Judiciary",
"House Judiciary",
"House Judiciary",
"House Judiciary",
"Senate Appropriations",
"Senate Appropriations",
"Senate Appropriations",
"Senate Appropriations",
"Senate Appropriations",
"Senate Oversight",
"Senate Oversight",
"Senate Oversight",
"Senate Oversight",
"Senate Oversight"),
n = c(4,8,4,6,2,7,4,8,2,8,1,4,3,6,4,8,4,3,8,7))
df <- df %>%
mutate(across(c(1:2), factor)) %>%
arrange(Year)
I made a plot to visualize the change in total engagements over these five years with the code below:
library(ggplot2)
plot <- df %>%
ggplot(aes(Year, n, group = Committees, color = Committees)) +
geom_line() +
geom_point() +
theme_bw ()
This already looks quite cluttered, and with 49 categories the plot with the original data looks like this.
So, I am trying to turn the plot into a plotly to make the lines more visible, to compress the legend into a dropdown, and to allow for some level of interactivity for my users.
library(plotly)
plot %>%
ggplotly(x = ~date, y = ~median,
split = ~city,
frame = ~frame,
type = 'scatter',
mode = 'lines')
Now, the problem is that making the buttons for 4 categories is simple enough with the code provided here. Also, this answer tackled the problem of having to create 49 different buttons per each category, and this answer further expanded it. However, I am not very well versed with plotly, and the code I built based on these answers just outputs: Error: object 'y_axis_var_names' not found
This is what I ended up with. If you have better methods to make the graph interactive and allow the selection of individual lines, please feel free to suggest it.
create_buttons <- function(df, y_axis_var_names) {
lapply(
y_axis_var_names,
FUN = function(var_name, df) {
button <- list(
method = 'restyle',
args = list(list(y = list(df[, var_name]),x = list(df[, var_name]))),
label = sprintf('Show %s', var_name)
)
},
df
)
}
y_axis_var_names <- c("House Foreign Affairs",
"House Judiciary",
"Senate Appropriations",
"Senate Oversight")
plot %>%
ggplotly(type = 'scatter',
mode = 'lines') %>%
layout(xaxis = list(domain = c(0.1, 1)),
yaxis = list(title = "y"),
updatemenus = list(
list(
y = 0.7,
buttons = create_buttons(plot, y_axis_var_names))))




date,median,city,frame? Andplotis not a dataframe, and you pass it to your functioncreate_buttons.