4
votes

TLDR: I want to label the frame slider with the three letter abbreviation instead of the number for each month.

I created a bar chart showing average snow depth each month over a 40 year period. I'm pulling my data from NOAA and then grouping by year and month using lubridate. Here is the code:

  snow_depth <- govy_data$snwd %>%
     replace_na(list(snwd = 0)) %>%
     mutate(month_char = month(date, label = TRUE, abbr = TRUE)) %>%
     group_by(year = year(date), month = month(date), month_char) %>%
     summarise(avg_depth = mean(snwd))

The mutate function creates a column (month_char) in the data frame holding the three letter abbreviation for each month. The class for this column is an ordered factor.

The code below shows how I'm creating the chart/animation:

snow_plot <- snow_depth %>% plot_ly(
    x = ~year, 
    y = ~avg_depth, 
    color = ~avg_temp, 
    frame = ~month,
    text = ~paste('<i>Month</i>: ', month_char,
                  '<br><b>Avg. Depth</b>: ', avg_depth, 
                  '<br><b>Avg. Temp</b>: ', avg_temp),
    hoverinfo = 'text',
    type = 'bar'
  )

snow_plot

This code generates a plot that animates well and looks like this:

snow chart

What I'd like to do is change the labels on the slider so instead of numbers, it shows the three letter month abbreviation. I've tried switching the frame to ~month_char which is the ordered factor of three letter month abbreviations. What I end up with, isn't right at all:

snow chart, bad

The data frame looks like:

snow-depth-df

1

1 Answers

4
votes

I fear, with the current implementation of animation sliders in R's plotly API the desired behaviour can't be realized. This is due to the fact, that no custom animation steps are allowed (this includes the labels). Please see (and support) my GitHub FR for further information.

This is the best I was currently able to come up with:

library(plotly)

DF <- data.frame(
  year = rep(seq(1980L, 2020L), each = 12), 
  month = rep(1:12, 41), 
  month_char = rep(factor(month.abb), 41),
  avg_depth = runif(492)
)

fig <- DF %>%
  plot_ly(
    x = ~year, 
    y = ~avg_depth,
    frame = ~paste0(sprintf("%02d", month), " - ", month_char),
    type = 'bar'
  ) %>%
  animation_slider(
    currentvalue = list(prefix = "Month: ")
  )

fig

(Edit from OP) Here's the resulting graph using the above code:

Snow Plot With Month Labels