I'd like to create an animated graph using plotly in R in a way in which my facets are displayed by selectiong on a dropdown list. I'm not sure if this can be done, I have seen something similar here but I've got around 30 different categories so doing the code one by one manually would take quite a lot of time...
Basically, my plots are line graphs showing timing (T0 to T8) of sightings of different species within different regions. I'd like to generate a graph in which I could select an Ecoregion and visualise lines showing the mean timing for each time point of a species in that region, that is one line per species present (no mater if there were 1 or 20 records) I've got the following graph
set.seed(123)
species <- rep(c("Species A", "Species B", "Species C"), each = 7)
ecoregions <- rep(letters[1:30], each = 2)
times <- rep(0:7, times = 3)
values <- matrix(rpois(21, 10), ncol = 3)
colnames(values) <- paste0("DaSS", 1:3)
Df2 <- data.frame(Tpoint = rep(values, each = length(ecoregions)),
Time = rep(times, times = length(ecoregions)),
Species = rep(species, times = length(ecoregions)),
Ecoregion = rep(ecoregions, each = length(times)))
This is my ggplot code for creating what I want with facets, but since there are many ecoregions these are tiny, so I'd like to create an interactive plot with plotly instead of facets
p<-Df2%>%
ggplot(aes(x = Times, y = values, group =Species, color=Species)) +
stat_summary(fun = "mean", geom = "line")+
#geom_smooth(method = "loess", se = TRUE) +
labs(title = "Amount of time by species and ecoregion",
x = "Time point",
y = "hours")+
theme_bw()+
theme(legend.position="bottom",
strip.text = element_text(size = 14), # Adjust strip text size
strip.background = element_blank(), # Remove strip background
panel.spacing = unit(1, "lines")
) +facet_wrap("Ecoregion")
I've used something like the below code but haven't had much luck...the data won't change when I use any of the buttons.
p <- Df2 %>%
group_by(Species, Ecoregion) %>%
#summarize(mean_Time = mean(Time)) %>%
plot_ly(x = ~Species, y = ~Time, color = ~Species, type = "scatter", mode = "lines") %>%
layout(
xaxis = list(title = "Species"),
yaxis = list(title = "Time"),
updatemenus = list(
list(type = "buttons",
showactive = FALSE,
buttons = button_list)
)
)
# Show the interactive plot
p
Any help would be appreciated!
Consider building a
restyle
button list that contains the subset values byEcoregion
with all plot aesthetics (x
,y
,color
,type
,mode
):