#' Function that returns interactive plot enabling the user to see counts of demographic data
#'
#' @param df
#'
#' @return
#' @export
#'
#' @examples
#' homework::demo_plot(survey_data)
demo_plot <- function(df)
{
df_survey_data <- df %>%
dplyr::select( d_urban:s_problem, d_marital:s_age)%>%
haven::as_factor()
plot_data <- df_survey_data %>%
tidyr::pivot_longer(d_urban:s_age , names_to = "var", values_to = "value") %>%
dplyr::group_by(var,value) %>%
dplyr::summarise(count = dplyr::n()) %>%
dplyr::ungroup() %>%
dplyr::mutate(value = ifelse(is.na(value), "Not applicable" , value )) %>%
dplyr::group_by(var) %>%
dplyr::arrange(desc(count), .by_group = TRUE)
for(i in 1:ncol(df_survey_data)){
if (i == 1){
button_list <- paste0("list(method = \"restyle\",args = list(\"transforms[0].value\", unique(plot_data$var)[",i,"]),label =unique(plot_data$var)[",i,"])")
} else {
button_list <- paste0(button_list,",list(method = \"restyle\",args = list(\"transforms[0].value\", unique(plot_data$var)[",i,"]),label =unique(plot_data$var)[",i,"])")
}
}
eval(parse(text = paste("chart_drop <- list(
type = \"dropdown\",
active = 0,
buttons = list(", button_list ,"))" , sep="")))
plot <- plotly::plot_ly(autosize = F,
width = 900,
height = 600,
plot_data ) %>%
plotly::add_bars(
x = ~value ,
y = ~count,
name = "count",
text = ~var,
transforms = list(
list(
type = 'filter',
target = ~var,
operation = '=',
value = unique(plot_data$var)[1])
)
) %>%
plotly::layout(
xaxis = list(title = "",
categoryorder = "array",
categoryarray = plot_data$count),
updatemenus = list(chart_drop)
)
return(plot)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.