Hi there. I'm trying to add some interactivity to my plotly charts using crosstalk (specifically using filter_checkbox and filter_select) and I've run into a bit of snag. I produce my plots firstly through ggplot then I convert it to plotly using ggplot function.
While I can generate the chart fine (and there's plenty of interactivity on the markdown), I have a couple of problems. Firstly, when I wish to filter (either via filter_select or filter_checkbox), the 'recent' data disappears from the chart entirely, and cannot be recovered without refreshing the html. A similar thing happens with the actual data I'm filtering; I cannot revert the chart to its original state without refreshing the page.
Does anyone know why this might be? Copy of my code + data is below.
Below is a snippet of my data (data=historic):
structure(list(date = c("23-03-2019", "23-03-2019", "23-03-2019",
"23-03-2019", "05-05-2020", "05-05-2020", "05-05-2020", "05-05-2020",
"17-06-2021", "17-06-2021", "17-06-2021", "17-06-2021"), cumvol = c(0.004,
0.034, 0.054, 0.057, 0.005, 0.048, 0.068, 0.075, 2.009, 2.029,
2.049, 2.064), time = structure(c(26457, 26636, 26658, 27216,
25152, 25614, 25667, 25668, 56966, 57268, 57303, 58986), units = "secs", class = c("hms",
"difftime")), Year = c("2019", "2019", "2019", "2019", "2020",
"2020", "2020", "2020", "2021", "2021", "2021", "2021"))
On top of this I plot another line from a separate df (data=recent).
structure(list(date = structure(c(19038, 19038, 19038, 19038), class = "Date"),
cumvol = c(0.029, 0.034, 0.07, 0.075), time = structure(c(29674, 29674, 29691, 29719),
class = c("hms", "difftime"), units = "secs")), Year = c("2022", "2022", "2022", "2022"))
I then convert the data to Shared data, create a ggplot using that data, then covert that plot to ggplot as follows (the variable "most_recent" refers the to the most recent entry in the 'recent' dataframe):
sharedhistoric <- SharedData$new(historic, key = ~Date)
sharedrecent <- SharedData$new(recent, key = ~Date)
plot <- ggplot()+geom_line(data=sharedhistoric,aes(x=time, y=cumvol, group=date),color='#BAB0AC', alpha=0.5)+
geom_line(data=sharedrecent ,aes(x=time, y=cumvol, group=date),size=1.2,color='#E15758')+
geom_point(data=most_recent, aes(x=time,y=cumvol), color='#E15759',size=3)+geom_hline(yintercept = 0)+ theme(title=element_text(size=12),panel.background = element_rect(fill='white',color='black'),legend.position='right')+
labs(title = "Vol",subtitle = "Cum Vol so far", x = "Time", y = "Vol")
Finally, I convert the chart to plotly and use the following bcols:
chartyplot <- plotly::ggplotly(plot)
bscols(widths = c(4, 9),
list(
crosstalk::filter_checkbox("Year",
label = "Select Year",
sharedhistoric,
group = ~Year),
crosstalk::filter_select("Date",
label = "Date",
sharedhistoric,
group = ~Date)
), chartyplot)
Grateful for any advice/assistance.